데일리로그C:
article thumbnail
Published 2023. 4. 27. 18:26
스프링 프로젝트 생성 JAVA/spring

프로젝트 생성

1. 설정

프로젝트명 우클릭 > properties >

 1) java compiler : use 체크해제, 11 로 수정 apply

 2) project facets : java 11 수정 apply

 3) java build path : Classpath 클릭 후 우측 add library 클릭  > junit 4로 연결 apply

 

2. spring 프레임워크 버전 수정 - pom.xml에서

<properties> 안에

 1) java-version : 11

 2) spring-framework-version : 5.0.7

두번째 plugin 안에

 3)  version : 3.5.1

 4) source, target : 11

 

3. mysql jar 연동

 ㄴ> pom.xml 에 <dependency> 추가

 ㄴ> mysql db 생성

 ㄴ> class파일 생성(MySQLConnectionTest)

 ㄴ> junit test

 

4. lombok

 ㄴ> 설치 : spring 연결

 ㄴ> pom.xml 에 <dependency> 추가

 

5. mybatis 연동

 ㄴ> pom.xml 에 <dependency> 추가

 ㄴ> src / main / webapp / WEB-INF / spring / root-context.xml

       1) Namespaces 에서 4개 체크(beans, context, jdbc, mybatis-spring)

       2) Source 에서 아래 코드 추가

<!-- Root Context: defines shared resources visible to all other web components -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    <property name="url" value="jdbc:mysql://localhost:3306/spring"></property>
    <property name="username" value="root"></property>
    <property name="password" value="1111"></property>
</bean>

<!-- 추가 구문 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <!-- 두번째 추가 구문 -->
    <property name="configLocation" value="classpath:/mybatis-config.xml"></property>
</bean>

 ㄴ> class파일 생성(DataSourceTest)

 ㄴ> junit test

 ㄴ> root-context.xml 추가 구문 입력

 ㄴ> main/resources 에 mybatis-config.xml 생성

 ㄴ> root-context.xml두번째 추가 구문 입력

 ㄴ> class 파일 생성(MybatisTest

 ㄴ> junit test

 

6. mappers 패키지 생성

  ㄴ> src/main/resources

 


기본 구성

 

[ src/main/java ]  --> 작성되는 코드의 경로
  - 프로젝트 만들때 작성한 경로 자동으로 생성(org.zerock.controller)
  - org.zerock.controller 에 class 생성할 것!!
  - 기본 생성 : HomeController.java
      ㄴ>  forward index 

< HomeController.java >

package org.zerock.controller;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	
	@RequestMapping(value = "/", method = RequestMethod.GET) // get 방식이라면 안에 있는것을 실행하겠다
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		// request.setattribute 대신 사용
		
		return "index"; // index.jsp 에 serverTime 전달(forward할때 수정)
	}
	
}

 

[ src/main/resources ] --> 실행할 때 참고하는 기본 경로(주로 설정 파일)
  - 기본 생성 : log4j.xml
  - mybatis-config.xml

< mybatis-config.xml >

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE configuration
	PUBLIC "-//mybatis.org//DTD Config 3.0//En"
	"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

</configuration>

 

< mybatis-spring > 
1. mybatis
  ㄴ> sql, mapping 프레이워크로 별도의 설정파일 가질 수 있음
  ㄴ> 자동으로 connection close(); 처리
  ㄴ> 내부적으로 PreparedStatement 처리
  ㄴ> 리턴 타입을 지정하는 경우 자동으로 객체 생성 및 RestulSet 처리
  ㄴ> 가장 핵심적인 객체 : SQLSession 이라는 존재와 SQLSessionFactroy
          1) SQLSessionFactroy : 내부적으로 SQLSession 이라는 것을 만들어 내는 존재.
          2) SQLSession를 통해 Connection 을 생성하거나 원하는 SQL 을 전달하고, 결과를 리턴 받는 구조로 작성

2. mybatis-spring 연동
  ㄴ> 연동 작업의 핵심 : Connecton 생성, 처리하는 SQLSessionFactroy의 존재
  ㄴ> SQLSessionFactroy : 데이터베이스와의 연결과 SQL의 실행에 대한 모든 것을 가진 가장 중요한 객체

 

[ src/test/java ] --> 테스트 코드를 넣는 경로  (변경 후 Run as > Junit test 하기)
  - MySQLConnectionTest.java  : mysql 연결 테스트  (01)
  - DataSourceTest.java : beans, context, jdbc, mybatis-spring source 수정후 테스트 (02)
  - MybatisTest.java : mybatis 테스트 (03)

 

[ src/test/resources ] --> 테스트 관련 설정 파일 보관 경로
  - 기본 생성 : log4j.xml

 

[ Maven Dependencies ] --> jar 파일 모아놓는 폴더
  - pom.xml 에 jar 파일 maven에서 복사한 내용을 적으면 설치됨 (생성됐는지 확인만 하면 됨)

 

[ src ] --> jsp, xml 파일 경로

    [ main / webapp ]
           [ resources ] - img 폴더 , css 등등
           [ WEB-INF ] 
                 [ classes ]
                 [ spring ]
                      [ appServlet ]  - servlet-context.xml
                      root-context.xml
                 [ views ] : index.jsp
                 web.xml
    [ test ]

< servlet-context.xml

  ㄴ> resources, forward 담당

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" /> <!-- forward 주소 -->
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<context:component-scan base-package="org.zerock.controller" />
	
	
	
</beans:beans>

 

< root-context.xml >

  ㄴ> sql 담당(db명 입력)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
		http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/spring"></property>
		<property name="username" value="root"></property>
		<property name="password" value="1111"></property>
	</bean>
	
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property> <!--위의 bean datasource를 가져와서 변수를 쓰겠다  -->
		<property name="configLocation" value="classpath:/mybatis-config.xml"></property>
	</bean>
</beans>

 

pom.xml
  ㄴ> jar 담당
        http://mvnrepository.com/  해당 파일 설치사이트 들어가서 아래 Maven 복붙하기
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.zerock</groupId>
	<artifactId>controller</artifactId>
	<name>ex00</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>11</java-version>
		<org.springframework-version>5.0.7.RELEASE</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</org.slf4j-version>
	</properties>
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				 </exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
				
		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>	
		
		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
				
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	
		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.10</version>
			<scope>test</scope>
		</dependency>
		
		<!-- 추가되는 내용들(jar) Maven Dependencise 폴더(?)에 들어가는지 확인할것 -->
		<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
		<dependency>
		    <groupId>org.projectlombok</groupId>
		    <artifactId>lombok</artifactId>
		    <version>1.18.26</version>
		    <scope>provided</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
		<dependency>
		    <groupId>com.mysql</groupId>
		    <artifactId>mysql-connector-j</artifactId>
		    <version>8.0.32</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis</artifactId>
		    <version>3.4.6</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis-spring</artifactId>
		    <version>1.3.2</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-jdbc</artifactId>
		    <version>${org.springframework-version}</version>
		</dependency>

		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-test</artifactId>
		    <version>${org.springframework-version}</version>
		</dependency>
		        
	</dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

 

(01) mysql 연결

<  mysql 에서 >

create database spring; // 데이터 베이스 생성

 ㄴ>  root-context.xml 첫번째 bean에 db명 입력하기

 

< MySQLConnectionTest.java >  

package org.zerock.controller;

import java.sql.Connection;
import java.sql.DriverManager;

import org.junit.Test;

public class MySQLConnectionTest {

	// static 정적
	// final 상수(변경 절대 x) 변수명 대문자로
	private static final String URL = "jdbc:mysql://localhost:3306/spring"; //spring : 데이타베이스명
	private static final String USER = "root";
	private static final String PW = "1111";
	
	@Test //이 부분 오류가 생긴다면 JUnit 4 추가

	public void testConnection() throws Exception{

		//Class.forName(DRIVER);

		try{
			Connection con = DriverManager.getConnection(URL,USER,PW); 
			System.out.println(con); //객체가 가지고 있는 주소값이 출력된다.

			con.close(); 

		}catch(Exception e) {
			e.printStackTrace();
		}
	}
}

 

★ 정리 ★

| static
 ㄴ> 정적
 ㄴ> 객체가 아닌 '클래스'에 고정되어 있는 변수 or 메소드

| final
 ㄴ> 클래스,메소드,변수에 사용
 ㄴ> 클래스 
      ㆍfinal 붙어있는 클래스 상속 x
      ㆍ다른 클래스 상속하는데 final이 붙어있다면 오버라이딩으로 수정 x
 ㄴ> 변수
      ㆍ초기화 한번만

★ 설정 ★
- 프로젝트명 우클릭 > build path > configure build path > libraries - classpath 클릭 > add library > junit 4

// juit 4 : spring
// juit 5 : spring boot

- run as > junit test

 


logger

ㄴ> get/post 방식 모두 가능

ㄴ> System.out.println("==console==")와 같은 역할

ㄴ> 클래스 정보 등 부가적인 것들을 함께 볼 수 있음

ㄴ> 시스템 아웃 콘솔에만 출력하는 것이 아니라, 파일이나 네트워크 등, 로그를 별도의 위치에 남길 수 있음

       특히, 파일로 남길 때에는 일별, 특정 용량에 따라 로그를 분할하는 것도 가능

@Controller
public class HomeController {
	
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    @RequestMapping(value = "/", method = RequestMethod.GET) // get 방식이라면 안에 있는것을 실행하겠다
    public String home(Locale locale, Model model) {

    	logger.info("logger.info");
        
        return "index"; // index.jsp 에 serverTime 전달(forward할때 수정)
    }
}

========= console ======== 
INFO : org.zerock.controller.HomeController - logger.info

 


 

< HomeController.java > 

  ㄴ> 경로 : src/main/java > org.zerock.controller > homecontroller.java

  ㄴ> mvc2 에서 index.servlet 과 같다고 보면 됨

package org.zerock.controller;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	
	@RequestMapping(value = "/", method = RequestMethod.GET) // get 방식이라면 안에 있는것을 실행하겠다(post라면 RequestMethod.post)
	@GetMapping("/") // requestMapping과 동일
	
	public String home(Locale locale, Model model) { // home이라는 메소드 안에 class라는 객체 locale(Member m 과 같음)
		//logger.info("Welcome home! The client locale is {}.", locale);
		
		//Date date = new Date();
		//DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		//String formattedDate = dateFormat.format(date);
		
		//model.addAttribute("serverTime", formattedDate );
		// request.setattribute 대신 사용
		
		logger.info("logger.info");
		System.out.println("syso");
		
		
		return "index"; // index.jsp 에 serverTime 전달(forward할때 수정)
	}
	
}

 

< index.jsp >

  ㄴ> 경로 : src > main > webapp > WEB-INF > views > index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
index page <br>
<img src="/resources/img/cat01.jpg"> <br>
<img src="/img/cat01.jpg"> <br>
</body>
</html>

 


리턴타입

1. void

:  return 값 x  --> doA.jsp forward

 

< SimpleController.java  >

package org.zerock.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class SimpleController {

	@RequestMapping("doA")
	public void doAget() {
		// void는 리턴값이 없으므로 doA.jsp라는 주소값을 forward함
	}
}

 

 

2. String 

: return 값 o  --> 주소값은 doB이지만, forward는 return 값으로

 

< SimpleController.java  >

package org.zerock.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class SimpleController {

    @RequestMapping("doB")
        public String doBget() {
            return "index"; // return 이 있다면 return의 값.jsp로 forward
        }
}

 

주소값은 doB이지만 보여지는건 forward 된 index

 


 

변수 전달

주소?변수=값  --> java든 뭐든 그 변수를 받아야함(String msg)

 

변수 전달하는 방법

1) String msg 변수를 받아서 어노테이션 사용

public String doBget(@ModelAttribute("msg") String msg) {
		logger.info("msg:"+msg); // console에 적힘
		
		return "index"; // return 이 있다면 return의 값.jsp로 forward
	}
}

2) Model 객체 사용하기

@RequestMapping("doB")
	public String doBget(Model model) {  // model 클래스 타입으로 model 객체 생성
		logger.info("msg:"+msg); // console에 적힘
		model.addAttribute("mmm", msg); // msg라는 객체를 mmm이름으로 추가
		
		return "index"; // return 이 있다면 return의 값.jsp로 forward
	}
}

 

< SimpleController.java  >

package org.zerock.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class SimpleController {
	private static final Logger logger = LoggerFactory.getLogger(SimpleController.class);

    @RequestMapping("doB")
        public String doBget() {
            logger.info("msg:"+msg); // console에 적힘
            model.addAttribute("mmm", msg); // msg라는 객체를 mmm이름으로 추가
            model.addAttribute("id", "1111"); //1111 value를 id이름으로 추가

            return "index"; // return 이 있다면 return의 값.jsp로 forward
        }
}


=======console ========
INFO : org.zerock.controller.SimpleController - msg:abc

 

< index.jsp >

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- el 사용 -->
msg : ${msg} <br>  <!-- msg 객체 -->
mmm : ${mmm} <br>  <!-- msg 객체가 담겨져 있는 mmm -->
id : ${id} <br>    <!-- 1111이란 값이 담겨져 있는 id -->

</body>
</html>

 

★ 정리 ★

Model : 객체
 ㄴ> Controller 에서 생성된 데이터를 담아 View 로 전달할 때 사용하는 객체
 ㄴ> Servlet의 request.setAttribute() 와 비슷한 역할을 함
 ㄴ> addAttribute("key", "value") 메서드를 이용해 view에 전달할 데이터를 key, value형식으로 전달

@ModelAttribute("파라미터명")
 ㄴ> 요청 파라미터를 받아서 필요한 객체를 만들고 그 객체에 값을 넣어줘야함
 ㄴ> HTTP Body 내용과 HTTP 파라미터의 값들을 Getter, Setter, 생성자를  통해 주입하기 위해 사용
 ㄴ> 일반 변수의 경우 전달이 불가능하기 때문에 model 객체를 통해서 전달해야 한다.


* 참고
@RequestParam을 사용해서 값을 받고, set을 사용해서 값을 넣어주곤 하지만
이 과정을 자동화시켜주는 것이 @ModelAttribute이다.

★ 정리 ★
model.addAttribute("String name", Object value)
 ㄴ> value 객체를 name 이름으로 추가함
model.addAttribute(Object value)
 ㄴ> value객체를 추가함. 단순 클래스 이름을 모델이름으로 사용(소문자로)

 

★ 예시 ★

@ModelAttribute 사용 x 경우

   ㄴ> @RequestParam을 통해 요청 파라미터를 받음

   ㄴ> 하나씩 받아서 set을 해줘야 값이 저장됨

public void item(@RequestParam String name, @RequestParam int price, Model model){
    Item item = new Item();
    item.setName(name);
    item.setPrice(price);
    model.addAttribute("item", item);
}

 

@ModelAttribute 사용

   ㄴ> 요청 파라미터의 이름으로 Item 객체의 프로퍼티를 찾는다. 

   ㄴ> 해당 프로퍼티의 setter를 호출해서 파라미터 값을 입력한다.

   ㄴ> model.addAttribute도 생략 가능  @ModelAttribute를 사용함으로써 model에도 자동적으로 객체가 추가 되기 때문

public void modelAttributeEx(@ModelAttribute Item item, Model model){
	model.addAttribute("item", item);
}

 

★ 예제1 ★

< Member.java >

package org.zerock.controller;

import lombok.Data;

@Data
public class Member {

	private String id;
	private String pass;
	
}

 

< SimpleController.java  >

package org.zerock.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class SimpleController {
	private static final Logger logger = LoggerFactory.getLogger(SimpleController.class);
    
    @RequestMapping("doD")
	public String doDget(Model model) { // 메소드에 넣으면 자동적으로 초기화됨
		logger.info("==doD get==");
		
		Member m = new Member();
		m.setId("1111");
		m.setPass("2222");
		
		model.addAttribute(m); // 객체없이 넘길때
		model.addAttribute("m", m); // m이라는 객체를 jsp에서 사용할 수 있는 객체로 넘기겠다
		
		System.out.println("m.tostring : "+m.toString());
		
		return "index"; // return 이 있다면 return의 값.jsp로 forward
	}
}


======= console ==========
m.tostring : Member(id=1111, pass=2222)

 

< index.jsp >

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- model.addAttribute("m", m); 로 했을 때 -->
m.id = ${m.id } <br>
m.pass = ${m.pass} <br>
==================================== <br>
<!-- model.addAttribute(m); 로 했을 때 : 알아서 Member 객체의 소문자로 객체를 지정해줌(member) -->
member.id = ${member.id } <br>
member.pass = ${member.pass} <br>

</body>
</html>

 

★ 예제2 ★

< ProductVO.java >

package org.zerock.controller;

import lombok.Data;

@Data
public class ProductVO {

	private int price; //상품가격
	private String name; //상품명
}

 

< SimpleController.java  >

package org.zerock.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class SimpleController {

	private static final Logger logger = LoggerFactory.getLogger(SimpleController.class);
	
	@RequestMapping("doD")
	public String doDget(Model model) { // 메소드에 넣으면 자동적으로 초기화됨
		logger.info("==doD get==");
		
		ProductVO p = new ProductVO();
		p.setPrice(2000);
		p.setName("고구마");
		
		model.addAttribute(p);
		model.addAttribute("p", p); // 객체, 변수
		
		return "index"; // return 이 있다면 return의 값.jsp로 forward
	}
	
	
}

 

< index.jsp > 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

productVO.price : ${productVO.price} <br>
productVO.name : ${productVO.name} <br>
================================= <br>
p.price : ${p.price} <br>
p.name : ${p.name} <br>


</body>
</html>

 

경로

1. 각각 경로 설정

@RequestMapping("/member/doA")

@RequestMapping("/member/doB")

 

2. 묶어서 부모로 빼놓기 --> return에는 따로 절대경로 해줘야함

@RequestMapping("/member") // 부모로 빼놓을 수 있음
public class SimpleController {

 	@RequestMapping("doA") // 자식
    public void doAget() {
		
	}
    
    @RequestMapping("doB") // 자식
	public String doBget(@ModelAttribute("msg") String msg, Model model) {  
		logger.info("msg:"+msg); // console에 적힘
		model.addAttribute("mmm", msg); // msg라는 객체를 mmm이름으로 추가
		model.addAttribute("id", "1111"); // 1111 value를 id이름으로 추가
		
		return "/meber/index"; // 별도(절대경로로 처리- member폴더 안에 있는 index로 감)
	}
}

 

 

★ 참고사항 ★

* 트랜잭션 : 여러개를 동시에 insert 하는데 그중 하나라도 실패하면 실행못하게 막는 것

* import 처리 ctrl + shift + o

* 경로 정리  "나" <------------------------> "상대방"
- 상대경로 : 내기준으로 상대방이 있는 곳까지 직접 가서 데리고 다시 원위치하며 길 알려주는것
- 절대경로 : 내 기준이 아닌 상대방 기준으로 알려주는것(내가 설명해주러 갈 필요 x)

* model 에 해당하는 class 파일 -->  파일명VO

* always 체크한 이후로 run on server 창이 안뜨는 경우
  - 프로젝트명 우클릭 > properties > server > none 선택 후 apply and close 

 

'JAVA > spring' 카테고리의 다른 글

스프링 Board 구현_넘버링, 검색  (0) 2023.05.03
스프링 Board 구현_예외처리, 페이징  (1) 2023.05.02
스프링 Board 구현  (0) 2023.04.28
스프링 페이지 이동(변수 전달)  (0) 2023.04.28
스프링 설치 및 설정  (0) 2023.04.27
profile

데일리로그C:

@망밍

포스팅이 도움됐다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

profile on loading

Loading...