※ SimpleFormController



그림1) SimpleFormController의 처리 과정


그림2) sessionForm 프로퍼티가 true인 경우, 커맨드 객체를 HttpSesstion에 저장

■ formBackingObject()메서드
  - 커맨드 객체 기본 값 처리 : HTTP GET 요청이 들어오거나 POST요청이 들어오는 경우 formBackingObject() 메서드를 호출하여 커맨드 객체를 생성
  - POST 요청인 경우에는 요청 파라미터 값을 생성된 커맨드 객체에 반영한 뒤 폼 전송 요청을 처리
  - formBackingObject() 메서드가 생성한 커맨드 객체는 HTTP GET요청이나 POST 요청인 경우 모두 뷰에 전달되어 사용될 수 있다. 따라서 폼을 출력할 때 기본 값을 출력해 주어야 한다면 해당 메서드를 오버라이딩 하면 됨

■ onSubmit()메서드
  - POST 요청의 처리


package bean;

public class UserBean {
 String userId;
 String passWord;
 String userName;
 String address;
 String nickName;

 
 //get, set 생략
 ......

 
 @Override
 public String toString() {
  return "UserBean [address=" + address + ", nickName=" + nickName
    + ", passWord=" + passWord + ", userId=" + userId
    + ", userName=" + userName + "]";
 }
 
}



package controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import bean.UserBean;

public class UserSimpleFormController extends SimpleFormController {

 @Override
 protected Object formBackingObject(HttpServletRequest request) throws Exception {
  // TODO Auto-generated method stub
  System.out.println("<<<<< formBackingObject >>>>>");
  System.out.println("request method = " + request.getMethod());
  
  UserBean userBean = new UserBean();;
  
  if(request.getMethod().equals("GET")){     //GET
   userBean.setUserId("ID 입력");
   userBean.setPassWord("password 입력");
   userBean.setUserName("Name 입력");
   userBean.setAddress("Address 입력");
  }else{                                    //POST
   userBean.setNickName("위대한 탄생");
  }
  
  return userBean;
 }
 
 @Override
 protected ModelAndView onSubmit(HttpServletRequest request,
   HttpServletResponse response, Object command, BindException errors)
   throws Exception {
  // TODO Auto-generated method stub
  System.out.println("<<<<< onSubmit >>>>>");
  
  //로직구현
  UserBean userBean = (UserBean)command;
  System.out.println("param print : " + userBean.toString());
  
  try{
   ModelAndView modelAndView = new ModelAndView();
   modelAndView.setViewName(getSuccessView());
   modelAndView.addObject("userBean", userBean);
   
   //throw new Exception();
   return modelAndView;
   
  }catch(Exception e){
   System.out.println("Exception => " + e.toString());
   return showForm(request, response, errors);
  }
  
 }
}



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


 <!-- HandlerMapping -->
 <bean id="simpleUrlHandlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
  <property name="mappings">
   <props>
    <prop key="/userReg.sp">userSimpleFormController</prop>
   </props>
  </property>
 </bean>

 
 <!-- ViewResolver -->
 <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="viewClass">
   <value>org.springframework.web.servlet.view.JstlView</value>
  </property>
  <property name="prefix">
   <value>jsp/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>
 
 
 <bean id="userSimpleFormController" class="controller.UserSimpleFormController">
  <property name="commandClass" value="bean.UserBean"></property>
  <property name="commandName" value="userBean"></property>
  <property name="formView" value="userReg"></property>
  <property name="successView" value="userRegSuccess"></property>

 </bean>
 
</beans>



userReg.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page session="false" %>   
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@page import="bean.UserBean"%>
<html>

<head>
<title>User Reg Page</title>
<%
 UserBean userBean = (UserBean)request.getAttribute("userBean");
 System.out.println("jsp print : " + userBean.toString());
%>
</head>
<body>
 <div align="center">
  <h2>회원 가입</h2>
  <form action="userReg.sp" method="post">
  <table border="1">
   <tr height="30px">
    <td>ID</td>
    <td>
     <input type="text" name="userId" value=""/>
    </td>
   </tr>
   <tr height="30px">
    <td>PW</td>
    <td>
     <input type="password" name="passWord" value=""/>
    </td>
   </tr>
   <tr height="30px">
    <td>성명</td>
    <td>
     <input type="text" name="userName" value=""/>
    </td>
   </tr>
   <tr height="30px">
    <td>주소</td>
    <td>
     <input type="text" name="address" value=""/>
    </td>
   </tr>
  </table>
  <table>
   <tr>
    <td><input type="submit" name="submit" value="reg"></input></td>
    <td><input type="reset" name="reset" value="reset"></input></td>
   </tr>
  </table>
  </form>
 </div>
</body>
</html>



userRegSuccess.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page session="false" %>   
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

<html>
<head>
<title>User Reg Page</title>
</head>
<body>
 <div align="center">
  <c:out value="${userBean.userName}"></c:out> 님.<br>
  회원가입을 진심으로 축하드립니다.
 </div>
</body>
</html>



log 출력

GET 방식일 경우
<<<<< formBackingObject >>>>>
request method = GET
jsp print : UserBean [address=Address 입력, nickName=null, passWord=password 입력, userId=ID 입력, userName=Name 입력]


POST 방식일 경우
<<<<< formBackingObject >>>>>
request method = POST
<<<<< onSubmit >>>>>
param print : UserBean [address=서울 관악, nickName=위대한 탄생, passWord=123, userId=snoopy, userName=스누피]


onSubmit()메소드에서 Exception 발생 시 showForm(request, response, errors) 리턴 => userReg.jsp



[참고자료] 스프링 2.5 프로그래밍 (최범균)

+ Recent posts