SPRING

SPRING - GET, POST, @ModelAttribute

Note&pen 2018. 2. 7. 13:43

이번 포스팅에서는 JSP에서 form태그로

값을 보내고 컨트롤러에서 데이터를 처리하고

다시 화면으로 뿌려주는 것을 해보겠습니다.

그리고 같이 @ModelAttribute 어노테이션을

알아 보겠습니다.


먼저 jsp파일을 만들어서 form태그로 값을

보내줄수 있도록 합니다.

스프링을 공부하시는 분들이라면

이미 JSP는 공부하셨을거라 생각하고

form태그에 대한 자세한 설명은

하지 않겠습니다.


먼저 index.jsp 생성합니다


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
    String context = request.getContextPath();
    System.out.println(context);
%>    
<form action="<%=context%>/studentView" method="post">
    이름: <input type="text" name="name"><br/>
    나이: <input type="age" name="age"><br/>
    학년: <input type="gradeNum" name="gradeNum"><br/>
    <input type="submit" value="전송">
</form>
</body>
</html>
 
 
cs


12line 에서 sysout은 context에 무슨값이

담겨있는지 확인하기 위해 사용했습니다

getContextPath메소드는 프로젝트의

contextPath값을 반환합니다. 


다음 form태그에서 입력값들을 POST 방식으로

studentView로 액션합니다. 

다음 컨트롤러 보겠습니다.


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
39
40
41
42
43
44
45
46
47
48
package com.spring.ex;
 
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
@Controller
public class HomeController {
    
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
    
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        logger.info("Welcome home! The client locale is {}.", locale);
        
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        
        String formattedDate = dateFormat.format(date);
        
        model.addAttribute("serverTime", formattedDate );
        
        return "home";
    }
    @RequestMapping("/index")
    public String index() {
        return "index";
    }
    @RequestMapping("/studentView")
    public String studentView(@ModelAttribute("studentInfo") StudnetInformation studnetInformation){
    
    return "studentView";
    }
    
    
    
    
    
}
 
cs


38line 에서 @ModelAttribute 어노테이션은

커맨드 객체의 이름을 개발자가 변경 할 수 있습니다.

즉 StudentInformation 객체명을 "studentInfo" 로 변경 한겁니다.

다음 StudentInformation 클래스 생성해줍니다


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
package com.spring.ex;
 
public class StudnetInformation {
    
    private String name;
    private String age;
    private String gradeNum;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public String getGradeNum() {
        return gradeNum;
    }
    public void setGradeNum(String gradeNum) {
        this.gradeNum = gradeNum;
    }
 
}
 
cs


마지막으로 데이터를 뿌려줄 화면단을 만들어줍니다


1
2
3
4
5
6
7
8
9
10
11
12
13
14
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    이름 : ${studentInfo.name}<br/>
    나이 : ${studentInfo.age}<br/>
    학년 : ${studentInfo.gradeNum}<br/>
</body>
</html>
cs

이제 테스트를 해봅니다


주소창 URL은 http://localhost:9080/ex/index 로 입력해줘야

정상적으로 테스트 할수 있습니다.



이름 나이 학년 입력하고 전송버튼 누릅니다



전송버튼을 누르면 form 태그에서

입력한 데이터 값들을 확인 할수있습니다

이름은 한글이 깨졌습니다

스프링에서 한글처리 방법은 

다음 포스팅에서 하겠습니다.