Model 객체
컨트롤러에서 생성된 데이터를 담아 JSP에 전달하는 역할
Servlet에서 모델2 방식으로 데이터를 전달
request.setAttribute("serverTime", new java.util.Date());
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/home.jsp");
dispatcher.forward(request, response);
MVC에서 Model을 이용한 데이터 전달
public String home(Model model){
model.addAttribute("serverTime", new java.util.Date());
return "home";
}
@ModelAttribute
강제로 전달받은 파라미터를 Model에 담아서 전달하도록 할 때 필요한 어노테이션
1. Controller에서 @ModelAttribute로 int 값 전달
(package 및 import 생략)
@Controller
@RequestMapping("/sample/*")
@Log4j
public class SampleController {
(생략)
@GetMapping("/ex04")
public String ex04(SampleDTO dto, @ModelAttribute("page") int page) {
log.info("dto : " + dto);
log.info("page : " + page);
return "/sample/ex04";
}
}
2. 테스트를 위해 '/WEB-INF/views' 밑에 sample 폴더 생성
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text-html; charset=UTF-8">
<title>ex04</title>
</head>
<body>
<h2>SAMPLEDTO ${sampleDTO }</h2>
<h2>PAGE ${page }</h2>
</body>
</html>
3. 결과 확인
@GetMapping 어노테이션을 사용했으므로 URL 뒤에 직접 쿼리스트링 작성
( http://localhost:8080/sample/ex01?name=test&age=111&page=3 )
끝!
'Spring Framework > MVC' 카테고리의 다른 글
Controller Return Type (0) | 2021.01.11 |
---|---|
RequestMapping (0) | 2021.01.07 |
Controller (0) | 2021.01.07 |