2020.04.27 TIL 스프링 - Spring Form Tag 사용하기
Spring의 form 태그는 이렇게 prefix를 붙이고 modelAttribute를 추가하여 사용한다.
<form:form modelAttribute="student">
<form:input path="name">
// 자동으로 student모델의 getName()의 값이 초기 값으로 세팅되고, 이후에 submit을 하면 setName()이 호출된다. 언제나 case 유의할 것!
처음에 모델을 포함해서 HTML을 렌더링 해주는 controller는 아래와 같이 사용한다.
```
@RequestMapping("/showForm")
public String showForm(Model theModel) {
Student theStudent = new Student();
theModel.addAttribute("student", theStudent);
theModel.addAttribute("theCountryOptions", countryOptions);
return "student-form";
}
```
HTML 코드는 이러하고
```
<form:form action="processForm" modelAttribute="student">
Student first name: <form:input path="firstName"/><br>
Student last name: <form:input path="lastName"/><br>
<form:select path="country">
<form:options items="${theCountryOptions}"/>
</form:select>
<input type="submit" value="submit">
</form:form>
```
form을 request parameter로 받는 student는 이렇게 파싱한다.
```
@RequestMapping("/processForm")
public String processForm(@ModelAttribute("student") Student student) {
System.out.println("The student Name: " + student.getFirstName() + " " + student.getLastName());
return "student-confirmation";
}
```
마지막으로 request를 받아서 처리하고 리턴하는 controller가 보여주는 HTML은 아래와 같다.
```
Last Name of student: ${student.lastName} <br>
First Name of student: ${student.firstName} <br>
Origin of student: ${student.country}
<form:form modelAttribute="student">
<form:input path="name">
// 자동으로 student모델의 getName()의 값이 초기 값으로 세팅되고, 이후에 submit을 하면 setName()이 호출된다. 언제나 case 유의할 것!
처음에 모델을 포함해서 HTML을 렌더링 해주는 controller는 아래와 같이 사용한다.
```
@RequestMapping("/showForm")
public String showForm(Model theModel) {
Student theStudent = new Student();
theModel.addAttribute("student", theStudent);
theModel.addAttribute("theCountryOptions", countryOptions);
return "student-form";
}
```
HTML 코드는 이러하고
```
<form:form action="processForm" modelAttribute="student">
Student first name: <form:input path="firstName"/><br>
Student last name: <form:input path="lastName"/><br>
<form:select path="country">
<form:options items="${theCountryOptions}"/>
</form:select>
<input type="submit" value="submit">
</form:form>
```
form을 request parameter로 받는 student는 이렇게 파싱한다.
```
@RequestMapping("/processForm")
public String processForm(@ModelAttribute("student") Student student) {
System.out.println("The student Name: " + student.getFirstName() + " " + student.getLastName());
return "student-confirmation";
}
```
마지막으로 request를 받아서 처리하고 리턴하는 controller가 보여주는 HTML은 아래와 같다.
```
Last Name of student: ${student.lastName} <br>
First Name of student: ${student.firstName} <br>
Origin of student: ${student.country}
```
댓글
댓글 쓰기