프로그래밍 정리/Spring

MVC_Spring - @ModelAttribute 사용하기

Wooni0477 2019. 12. 31. 16:50
반응형
MVC_Spring - @ModelAttribute 사용하기



  • @ModelAttribute 사용하기

void 메소드(@modelAttribute("name") 객체 선언(value))


  • 실습과정

controller를 이용하여 index.jsp 이동 ->
index.jsp에서 post방식 값 전송->
controller에서 @modelAttribute를 이용하여 값전달 ->
studentView.jsp 값 보여줌



  • 예제를 통한 실습


-controller.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Controller
public class HomeController {
    
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
    
    @RequestMapping("/index")
    public String index() {
        return "index";
    }
    
    @RequestMapping("/studentView")
    public String studentView(@ModelAttribute("studentInfo") StudentInformation studentInformation){
        return "studentView";
    }
}
cs

@ModelAttribute("studentInfo") StudentInformation studentInformation)

서로 같은 뜻

StudentInformation studentInformation
ModelAndView mv = new ModelAndView();
mv.addObject("studentInfo", studentInformation);


-list.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>    
    <form action="/studentView" method="post">
        이름 : <input type="text" name="name"><br />
        나이 : <input type="age" name="age"><br />
        학년 : <input type="classNum" name="classNum"><br />
        반 : <input type="gradeNum" name="gradeNum"><br />
        <input type="submit" value="전송">
    </form>
</body>
</html>
cs

form을 이용하여 값을 post방식으로 전달


-studentView.jsp
1
2
3
4
5
6
7
8
9
10
11
12
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
이름 : ${studentInfo.name} <br />
나이 : ${studentInfo.age} <br />
학년 : ${studentInfo.classNum} <br />
반 : ${studentInfo.gradeNum}
</body>
</html>
cs


-StudentInformation.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
27
28
29
30
31
32
public class StudentInformation {
 
    private String name;
    private String age;
    private String gradeNum;
    private String classNum;
    
    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;
    }
    public String getClassNum() {
        return classNum;
    }
    public void setClassNum(String classNum) {
        this.classNum = classNum;
    }
}
cs


-출력

list.jsp



studentView.jsp



반응형