Spring MVC

문이빈·2023년 9월 19일
0
post-thumbnail

스프링 MVC

스프링 MVC도 컨트롤러를 사용하여 클라이언트의 요청을 처리한다.
스프링에서 DispatcherServlet 이 MVC에서 C(Control) 부분을 처리한다.
개발자가 처리할 부분은 클라이언트의 요청을 처리할 컨트롤러와 응답화면을 전송할 JSP나 Velocity 템플릿 등 뷰 코드이다.

스프링 MVC의 구성 요소

서블릿을 통해서 와야만 함 페이지에 .jsp는 x

1. DispatcherServlet

클라이언트의 요청을 전달 받는다
컨트롤러에게 클라이언트의 요청을 전달하고 Controller가 리턴한 결과값을 View에 전달하여 응답을 생성

2. HandlerMapping

클라이언트의 요청 URL을 어떤 Controller가 처리할지를 결정

3. Controller

클라이언트의 요청을 처리한 뒤 결과를 DispatcherServlet에 알려줌

4. ModelAndView

컨트롤러가 처리한 결과 정보 및 뷰 선택에 필요한 정보를 담는다.

5. ViewResolver

컨트롤러의 처리 결과를 생성할 뷰를 결정

6. View

컨트롤러의 처리 결과 화면을 생성
JSP나 Velocity 템플릿 파일등을 뷰로 사용

프로젝트를 만들고

project명에서 우클릭 - Spring - Add Spring Project Nature
project명에서 우클릭 - Configure - Convert to Maven Project

spring web
5.3.23

spring web MVC

사실상 spring web MVC만 있어도 Spring web은 필요없음 - 의존관계로 연결되어 있기 때문에

JSTL 2번째 가장 최신 버전

Spring MVC Project

dynamic web project로 생성

----------------------------pom.xml----------------------------

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>chapter06</groupId>
  <artifactId>chapter06</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <release>17</release>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.2.3</version>
      </plugin>
    </plugins>
  </build>
  
  <dependencies>
  
  	<!-- Spring -->
  	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-context</artifactId>
	    <version>5.3.23</version>
	</dependency>
	
	<!-- Spring Web (webMVC 하나만 있어도 됨)-->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-web</artifactId>
	    <version>5.3.23</version>
	</dependency>
	
	<!-- Spring Web MVC -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-webmvc</artifactId>
	    <version>5.3.23</version>
	</dependency>
	
	<!-- JSTL -->
	<dependency>
	    <groupId>javax.servlet</groupId>
	    <artifactId>jstl</artifactId>
	    <version>1.2</version>
	</dependency>
	
	<!-- Lombok -->
	<dependency>
	    <groupId>org.projectlombok</groupId>
	    <artifactId>lombok</artifactId>
	    <version>1.18.28</version>
	    <scope>provided</scope>
	</dependency>
	
  </dependencies>
</project>
----------------------------web.xml----------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>chapter06</display-name>
  
  <servlet>
  	<servlet-name>dispatcherServlet</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>dispatcherServlet</servlet-name>
  	<url-pattern>*.do</url-pattern>
  </servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

----------------------------dispatcherServelet-servlet.xml----------------------------
<?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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://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">

	<bean id="helloController" class="com.controller.HelloController"></bean>
</beans>

----------------------------servlet-context.xml----------------------------

<?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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://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">

	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- <property name="prefix" value="/view/"></property> 안쓸거면 mav.setViewName("/view/hello"); 사용-->
		<property name="suffix" value=".jsp"></property>
	</bean>
	
	<bean id="helloController" class="com.controller.HelloController"></bean>
	
</beans>

----------------------------HelloController.java----------------------------

package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller // 해줘야 handlerMapping에 의해서 찾을 수 있다.
public class HelloController {
	
	@RequestMapping(value = "/hello.do", method=RequestMethod.GET)
	public ModelAndView hello(){// 사용자(가 만든) 콜백 메소드 (스프링 컨테이너에 의해서 호출) ,메소드 명은 보통 hello.do 따라감
		ModelAndView mav = new ModelAndView();
		mav.addObject("result", "Hello Spring MVC!!");
		
		// 파일명 지정 => jsp의 파일은 -> /view/hello.jsp
		mav.setViewName("/view/hello");
		
		return mav;
	}
	
	// URL에서 바로 JSP가 실행되지 않게 하기 위해서 /WEB-INF에 JSP 파일을 작성한다.
	// http://localhost:8080/chapter06/WEB-INF//view2/hello2.jsp 같은 주소로 실행할 수 없다.
	@RequestMapping(value = "/hello2.do", method=RequestMethod.GET)
	public ModelAndView hello2() {
		ModelAndView mav = new ModelAndView();
		mav.addObject("result2", "Have a nice day!!");
		
		mav.setViewName("/WEB-INF/view2/hello2");
		
		return mav;
	}
	
	/* 스프링에서 return 타입이 String이면 단순 문자열이 아니라, JSP 파일명으로 인식한다.
	 * welcome.jsp 파일을 찾게 된다.
	 * 만약에 단순 문자열로 처리하고 싶으면 @ResponseBody를 써야한다.(resolver를 거치지말고 바로 view로)
	 *  */
	@RequestMapping(value = "/hello3.do", method=RequestMethod.GET, produces = "text/html; charset=UTF-8") // produces - 한글처리
	@ResponseBody
	public String hello3() {
		//return "welcome";
		return "안녕하세요";
	}

}

----------------------------HelloController.java----------------------------

<body>
<h1>${result }</h1>
</body>

Spring MVC Project

chapter6_1

----------------------------pom.xml----------------------------

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>chapter06_1</groupId>
  <artifactId>chapter06_1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <release>17</release>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.2.3</version>
      </plugin>
    </plugins>
  </build>
  
    <dependencies>
  
  	<!-- Spring -->
  	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-context</artifactId>
	    <version>5.3.23</version>
	</dependency>
	
	<!-- Spring Web MVC -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-webmvc</artifactId>
	    <version>5.3.23</version>
	</dependency>
	
	<!-- JSTL -->
	<dependency>
	    <groupId>javax.servlet</groupId>
	    <artifactId>jstl</artifactId>
	    <version>1.2</version>
	</dependency>
	
	<!-- Lombok -->
	<dependency>
	    <groupId>org.projectlombok</groupId>
	    <artifactId>lombok</artifactId>
	    <version>1.18.28</version>
	    <scope>provided</scope>
	</dependency>
	
  </dependencies>
</project>

----------------------------web.xml----------------------------

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>chapter06_1</display-name>
  
<servlet>
	<servlet-name>dispatcher</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	
  	<!-- 위치 또는 이름을 변경할 때 : /WEB-INF/spring/appServlet/servlet-context.xml-->
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
 	 </init-param>  
</servlet>
  
<servlet-mapping>
  	<servlet-name>dispatcher</servlet-name>
  	<url-pattern>*.do</url-pattern>
</servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

----------------------------servlet-context.xml----------------------------

<?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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://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">


	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="suffix" value=".jsp"></property>
		<property name="prefix" value="/WEB-INF"></property>
	</bean>

	<bean id="sumController" class="com.controller.SumController"></bean>
	
</beans>

----------------------------SumController.java----------------------------

package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class SumController {
	
	//@RequestMapping(value = "/input.do", method = RequestMethod.GET)
	@GetMapping(value = "/input.do")
	public String input() {
		return "/sum/input";
	}
	

	@RequestMapping(value = "/result.do", method = RequestMethod.GET)
	public String result() {
		return "/sum/result";
	}
    
    ->
	->@RequestMapping(value = "/result.do")
	->public ModelAndView result(@RequestParam int x, @RequestParam int y) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("x", x);
		mav.addObject("y", y);
		mav.setViewName("/sum/result");
		return mav;
	}
    
    // X or Y 빈칸에 아무것도 넣지 않으면 400 에러가 떨어져서 바꿔줌
	@RequestMapping(value = "/result.do")
	public ModelAndView result(@RequestParam (required = false, defaultValue = "0") String x, 
							   @RequestParam (required = false, defaultValue = "0") String y) { 
		ModelAndView mav = new ModelAndView();
		mav.addObject("x", x);
		mav.addObject("y", y);
		mav.setViewName("/sum/result");
		return mav;
	}
    
    // 받아와야 하는 값이 여러개가 된다면 map을 사용한다.
	@RequestMapping(value = "/result.do")
	public ModelAndView result(@RequestParam Map<String, String> map) { 
		ModelAndView mav = new ModelAndView();
		mav.addObject("x", map.get("x"));
		mav.addObject("y", map.get("y"));
		mav.setViewName("/sum/result");
		return mav;
	}
    
    // modelMap 사용.
		@RequestMapping(value = "/result.do")
		public String result(@RequestParam Map<String, String> map, ModelMap modelMap) {
			modelMap.put("x", map.get("x"));
			modelMap.put("y", map.get("y"));
			
			return "/sum/result";
		}
        // DTO를 만들어 사용하기
        @RequestMapping(value = "/result.do")
	public String result(@RequestParam SumDTO sumDTO, ModelMap modelMap) {
		modelMap.put("x", sumDTO.getX());
		modelMap.put("y", sumDTO.getY());
        -----------SumDTO-----------
        @Setter
		@Getter

		public class SumDTO {
	
		private int x;
		private int y;
        
        
    @RequestMapping(value = "/result.do")
	public String result(@ModelAttribute SumDTO sumDTO, Model model) {
		model.addAttribute("x", sumDTO.getX());
		model.addAttribute("y", sumDTO.getY());
		
		return "/sum/result";
	}

}

----------------------------input.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>
<form action="result.do" method="get">
<table border="1">
   <tr>
      <th>X</th>
      <td>
         <input type="text" name="x">
      </td>
   </tr>
   <tr>
      <th width="70">Y</th>
         <td>
             <input type="text" name="y">
         </td>
      </tr>
      <tr>
          <td colspan="2" align="center">
            <input type="submit" value="계산">
            <input type="reset" value="취소">
         </td>
      </tr>
</table>
</form>
</body>
</html>

----------------------------result.xml----------------------------

<%@ 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>
${param.x} + ${param.y} = ${param.x+param.y}

-> <h1>${x } + ${y } = ${x+y }</h1>
</body>
</html>

0개의 댓글