Spring/공부

[Spring MVC] Controller, Mapping 이해하기

하루인생 2021. 2. 1. 00:31

간단한 설명

@Controller : 클래스 위에 컨트롤러임을 표시한다, 맵핑을 위해 @RequestMapping 애노테이션을 함께 사용한다.

 

@RequestMapping : @RequestMapping("/user", method=RequestMethod.POST)와 같은 형식으로 사용한다.

스프링 버전 4.3이후 부터는 @GetMapping, @PostMapping, @PutMapping, @DeleteMapping를 지원한다.

 

 

코드로 이해하기

Controller와 Mapping 을 사용해보기 위해서 간단한 덧셈을 계산하는 Controller와 jsp파일을 만들었다.

package kr.or.connect.mvcexam.controller;


import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class PlusController {
	@GetMapping(path = "/plusform")
	public String plusform() {
		return "plusform";
	}
	@PostMapping(path = "/plus")
	public String plus(@RequestParam(name = "value1", required = true) int value1,
			@RequestParam(name = "value2", required = true) int value2, ModelMap modelMap) {

		// HttpServletRequest의 setAttribute()를 사용하여 값을 넘기면 되지만, 그렇게 되면 그쪽에 종속적이게 된다.
		// 그래서 이 방법 말고 spring이 제공하는 객체인 modelMap을 사용한다.
		// modelMap를 사용하면 spring이 알아서 request scope에 값을 넘겨준다.
		int result = value1  + value2;
		modelMap.addAttribute("value1", value1);
		modelMap.addAttribute("value2", value2);
		modelMap.addAttribute("result", result);
		
		return "plusresult";
	}
}

 /plusform 의 경로로 접속하면 컨트롤러는 plusform.jsp를 뷰로 반환하다. 이는 설정파일인 config 클래스에서 ViewResolver의 역할로 /WEB-INF/views/plusform.jsp를 실행하기 때문이다.

 

<!-- plusform.jsp -->
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
	<form method="post" action="plus">
		value1 : <input type="text" name="value1"><br>
		value2 : <input type="text" name="value2"><br>
		<input type="submit" value="확인"> 
	</form>
</body>
</html>

plusform.jsp파일이다. <form>태그에 값을 2개 넣고 확인을 누르면 action = "plus"를 처리한다.

이는 post형식으로 요청을 하고 있으므로 PlusController의 "/plus"를 매핑하는 plus() 메소드를 실행하여

결과적으로 plusresult.jsp 파일을 반환한다.

 

위 자바 코드에서 파라미터로 받은 값을 jsp 파일에 넘기기 위해서 modelMap을 사용했다.

ModelMap은 View에 data를 심어서 전달해준다(request scope).

그래서 해당 View에서는 EL표기법을 사용해서 그 값을 꺼내 사용할 수 있다.

 

 

Model , ModelAndView

Model : ModelMap과 같은 방법으로 사용한다. 차이점으로는 Model은 인터페이스인 반면에 ModelMap은 구현체이다. 결국 둘 중 아무거나 사용해도 상관없다.

	@PostMapping(path = "/plus")
	public String plus(@RequestParam(name = "value1", required = true) int value1,
			@RequestParam(name = "value2", required = true) int value2, Model model) {
		int result = value1  + value2;
		model.addAttribute("value3", 14);
		return "plusresult";
	}

 

ModelAndView : ModelAndView객체에 데이터와 뷰를 설정해서 반환한다. 결과적으로 ModelAndView객체를 반환

@PostMapping(path = "/addview")
	public ModelAndView addview(@RequestParam(name = "v1",required = true) int v1) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("addview");
		mav.addObject("v1", v1);
		return mav;
	}

setViewName()메소드로 뷰의 이름을 넣고, addObject("키",값) 메소드로 데이터를 넣는다. 이제 addview.jsp파일에서는 EL표기법으로 v1데이터를 사용할 수 있다.

주의할 점은 데이터를 등록할 때 Model과 ModelMap은 addAttribute를 사용하는 반면, ModelAndView는 addObject를 사용한다.