使用Spring MVC的表单控制器SimpleFormController
时间:2011-03-14
以注册过程为例,我们可能会选择继承AbstractController来实现表单的显示,继承AbstractCommandController来实现表单的处理 ,这样是可行的,但必须要维护两个控制器
在这种情况下,我们应该使用SimpleFormController,他接受GEt请求时显示表单,接受POST请求时处理表单,如果发生错误,控制器会知道重新显示这个表单,这样用户就可以修改错误,重新提交
表单对应的POJO
package model;
public class Student ...{
private String name;
private String sex;
public String getName() ...{
return name;
}
public void setName(String name) ...{
this.name = name;
}
public String getSex() ...{
return sex;
}
public void setSex(String sex) ...{
this.sex = sex;
}
}
控制器:
这个base类中还有一个DoSubmitAction()方法,和onSubmit()方法的区别就是后者可以返回一个ModelAndView对象,完成向页面输出数据的功能,而前者不能向页面返回数据,这两个方法同时只有一个有效
package Action;
import model.Student;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
public class RegisterStudentController extends SimpleFormController ...{
public RegisterStudentController()...{
this.setCommandClass(Student.class);
}
protected ModelAndView onSubmit(Object object, BindException arg1) throws Exception ...{
Student stu=(Student)object;
return new ModelAndView(getSuccessView(),"student",stu);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/train-service.xml,/WEB-INF/train-data.xml,/WEB-INF/train-servlet.xml</param-value>
</context-param>
<servlet>
<servlet-name>train</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>train</servlet-name>
<url-pattern>*.mvc</url-pattern>
</servlet-mapping>
<filter>
<filter-name>character</filter-name>
<filter-class>Action.CharacterFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>character</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
ê1ó?Spring MVCμ?±íμ¥?????÷Simpl |