1. DTO를 만들자 


어제만든 home.jsp에서 name, phone, email이라는 변수를 넘겨준다.

저번 글 링크 : https://welcomto-dd.tistory.com/42


-home.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" pageEncoding="UTF-8" %>
<html>
<head>
    <title>Home</title>
</head>
<body>
<h1>
    Hello world!  
</h1>
<P>  The time on the server is ${serverTime}. </P>
<h3><a href="hello.action">Spring 환영 메세지</a></h3>
<h3><a href="test/param.action?name=suzi&phone=010-123-1234&email=suzi@naver.com">GET방식 테스트</a> </h3>
 
<h3>2. Post방식 테스트</h3>
<form action="test/param.action" method="post">
이름:<input type="text" name="name"><br/>
전화:<input type="text" name="phone"><br/>
메일:<input type="text" name="email"><br/>
<input type="submit" value="전송"/><br/>
 
</form>
</body>
</html>
cs

: 13,17,18,19번째 줄에서 변수를 넘겨주는 것을 볼 수 있다.


-PersonDTO.java

1
2
3
4
5
6
7
8
9
10
package com.exe.springmvc;
 
public class PersonDTO {
    
    private String name;
    private String phone;
    private String email;
 
    //getter,setter는 생략...
}
cs

: 넘겨준 변수를 받아줄 DTO를 만들었다.


-실행화면

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.exe.springmvc;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
@Controller("test.controller")
public class TestController {
    
    @RequestMapping(value = "/test/param.action",method = {RequestMethod.POST,RequestMethod.GET})
    public String processPostRequest(PersonDTO dto, String name,HttpServletRequest request) {
        System.out.println("get/post 방식 Request");
        
        System.out.println(name);
        System.out.println(request.getParameter("phone"));
        
        System.out.println(dto);    //해시코드가 찍힘
        System.out.println("dto.getName(): "+dto.getName() );
        System.out.println("dto.getPhone(): "+dto.getPhone() );
        System.out.println("dto.getEmail(): "+dto.getEmail() );
        return "paramResult";
    }
}
cs

: 여기서 PersonDTO dto라는 매개변수를 추가해주고 system.out.println()으로 찍어서 출력해보자


-실행화면

: dto.setAttribute() 이런 작업 없이 스프링이 자동으로 잘 담아준 모습을 볼 수 있다!


**DTO를 만들어주고 변수이름을 맞춰주니 스프링이 알아서 DTO안에 넣어서 

주고받는 것을 알 수 있다.


2. 웹에서 한글 깨져 보일때 


-web.xml에 아래의 코드 추가해주자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 
    <!-- 생략...-->
 
    <!-- 한글 인코딩(웹에서 깨져보일때) -->
    <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>
</web-app>
cs


-실행화면

: 한글이 깨지지 않고 잘 나온다.


3. ModelAndView에 넣어서 DTO 보내기 


**ModelAndView는 view경로와 dto를 한번에 묶어서 보낼 수 있는 자료형이다.


-home.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" pageEncoding="UTF-8" %>
<html>
<head>
    <title>Home</title>
</head>
<body>
<!-- 생략 -->
<h3><a href="test/mav.action?name=shin&phone=010-234-5555&email=shin@naver.com">3. ModelAndView Get 테스트</a></h3>
 
<h3>4. ModelAndView Post 테스트</h3>
<form action="test/mav.action" method="post">
이름:<input type="text" name="name"><br/>
전화:<input type="text" name="phone"><br/>
메일:<input type="text" name="email"><br/>
<input type="submit" value="전송"/><br/>
</form>
</body>
</html>
cs


-TestController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.exe.springmvc;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
 
@Controller("test.controller")
public class TestController {
    
    //생략...
 
    @RequestMapping(value="/test/mav.action",method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView mavRequest(PersonDTO dto) {
        
        ModelAndView mav=new ModelAndView();
        mav.setViewName("paramResult");//view와
        mav.addObject("dto",dto);//dto를 함께 포장!!
        //dto는 여러개 보낼수 있다.
        //View는 하나여야한다.
        
        return mav;
    }
}
cs

: 여기서 ModelAndView mav라는 변수를 만들어서 보여줄 페이지인 view, 여기서는 paramResult.jsp 의 경로와,

dto를 담았다. 그리고 mav 리턴.


-paramResult.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<%@page import="com.exe.springmvc.PersonDTO"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<%
    request.setCharacterEncoding("UTF-8");
    String cp=request.getContextPath();
    
    String name=request.getParameter("name");//String을 받을때는 Parameter
    String phone=request.getParameter("phone");
    String email=request.getParameter("email");
    
    PersonDTO dto=(PersonDTO)request.getAttribute("dto");//Object를 받을때는 Attribute(모든객체 다 받을수 있다.)
    
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 
<h2>Param Result</h2>
이름:<%=name %><br/>
전화:<%=phone %><br/>
이메일:<%=email %><br/>
 
<br/><br/>
 
<h2>ModelAndView</h2>
<%if(dto!=null){ %>
이름:<%=dto.getName() %><br/>
전화:<%=dto.getPhone() %><br/>
이메일:<%=dto.getEmail() %><br/>
<%}else%>
    데이터없음
<%%>
</body>
</html>
cs

: dto를 TestController에서 보내줬기 떄문에 받아서 출력해준다.


**여기서 getParameter와 getAttribute의 차이

getParameter() : return값이 String만이 가능하다.

getAttribute() : return값으로 Object가 가능, 즉 모든 객체를 담을수 있음. 



4. Redirect 


**Redirect 쓰는 방법

1
2
3
4
5
6
    @RequestMapping(value="/test/redirect.action",method = {RequestMethod.GET,RequestMethod.POST})
    public String mavRedirectRequest(PersonDTO dto) {
        
        //return "redirect:/";    //홈으로 리다이렉트
        return "redirect:/hello.action";
    }
cs



+ Recent posts