◆ HTML 폼의 항목 이름과 자바빈 클래스의 프로퍼티 이름이 일치할 경우 폼에 입력한 값을 해당 자바빈 클래스의 프로퍼티 자동 설정
=> @RequestMapping 어노테이션이 적용된 메서드의 파라미터로 자바빈 타입을 추가 해주면 됨
◆ @ModelAttribute 어노테이션 : 컨트롤러의 처리 결과를 보여주는 뷰 코드에서 커맨드 객체의 클래스 이름을 이용해서 커맨드 객체에 접근
UserVO.java
package sp.mvc.vo;
public class UserVO { private String userName; private String address; private String telNumber; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getTelNumber() { return telNumber; } public void setTelNumber(String telNumber) { this.telNumber = telNumber; } @Override public String toString() { return "UserVO [userName=" + userName + ", address=" + address + ", telNumber=" + telNumber + "]"; } } |
UserController.java
package sp.mvc.controller;
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;
import sp.mvc.vo.UserVO;
@Controller public class UserController {
@RequestMapping(value="/userForm.sp", method=RequestMethod.GET) public String userForm(){ System.out.println("----- UserController.userForm()-----"); return "user/userForm"; } @RequestMapping(value="/userSave.sp", method=RequestMethod.POST) public String userSave(@ModelAttribute("userVo") UserVO userVo){ System.out.println("----- UserController.userSave(...) -----"); System.out.println(userVo.toString()); return "user/userInfo"; } } |
main_config.xml
userForm.jsp
<%@ 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>회원정보</title> </head> <body>
<form action="userSave.sp" method="post"> <table border="1"> <tr> <td>이름</td> <td><input type="text" name="userName" value=""/></td> </tr> <tr> <td>주소</td> <td><input type="text" name="address" value=""/></td> </tr> </table> <input type="submit" name="submit" value="전송"/> </form> </body> </html> |
userInfo.jsp
<%@ 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>회원정보</title> </head> <body>
<table border="1"> <tr> <td>이름</td> <td>${userVo.userName}</td> </tr> <tr> <td>주소</td> <td>${userVo.address}</td> </tr> </table>
</body> </html> |
결과
----- UserController.userForm()----- ----- UserController.userSave(...) ----- UserVO [userName=스누피, address=서울 강남 11-123, telNumber=null] |
userForm.jsp
userForm.jsp
userInfo.jsp
[참고자료] Spring 3.0 프로그래밍-최범균