STUDY/SPRING
스프링(3.0) DTO사용, 한글처리, ModelAndView
Anne of Green Galbes
2019. 4. 16. 16:30
예제 1 : DTO 사용
○ DTO를 만들어 놓으면 스프링이 알아서 DTO에 값을 넣는다.
- 단, 변수명이 동일해야한다.
- 스프링에게 DTO를 요청 후 사용 가능
@RequestMapping(value = "/test/param.action",method = {RequestMethod.GET,RequestMethod.POST})
public String processGetPostRequest(PersonDTO dto) {
System.out.println("Get/Post방식 Request");
System.out.println(dto);
System.out.println("name : " + dto.getName());
System.out.println("phone : " + dto.getPhone());
System.out.println("email : " + dto.getEmail());
return "paramResult";
}
예제 2 : POST방식 한글 처리
○ web.xml
- 파일 위치 : src > main > webapp > WEB-INF
- 한글 인코딩 설정
- filter의 filter-name과 filter-mapping의 filter-name은 같아야한다
- /* : 모든 주소는 POST방식일 때 한글처리를 한다
- GET방식은 한글이 깨짐
<filter>
<filter-name>CharsetEncoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharsetEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
예제 3 : ModelAndView Get / Post 방식
○ ModelAndView : 데이터(Model)과 jsp파일(View)를 한 세트로 반환값을 돌려줄 때 사용
- 스프링에만 있는 변수형
- jsp위에 dto를 얹어서 한번에 넘겨준다
TestController.java
@RequestMapping(value="/test/mav.action", method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView mavRequest(PersonDTO dto) {
ModelAndView mav = new ModelAndView();
//view(jsp파일)과 model(데이터)를 합치는 작업
mav.setViewName("paramResult"); //.jsp 생략
mav.addObject("dto",dto);
return mav;
}
paramResult.jsp
<%@page import="com.exe.springmvc.PersonDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%
request.setCharacterEncoding("UTF-8");
String cp = request.getContextPath();
PersonDTO dto = (PersonDTO)request.getAttribute("dto");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>ModelAndView로 넘어온 데이터</h2>
<%if(dto!=null) {%>
이름 : <%=dto.getName() %><br/>
전화 : <%=dto.getPhone() %><br/>
이메일 : <%=dto.getEmail() %><br/>
<%}else{ %>
ModelAndView로 넘어온 데이터 없음
<%} %>
</body>
</html>
예제 4 : 리다이렉트
○ redirect:/
- 원래 페이지로 돌아가는 return 값
- :/ 뒤에는 리다이렉트하고 싶은 페이지를 적어준다
- 뒤에 아무것도 적지 않으면 원래페이지 리다렉트
@RequestMapping(value="/test/redirect.action", method={RequestMethod.GET,RequestMethod.POST})
public String mavRedirectRequest(PersonDTO dto) {
return "redirect:/hello.action";
}