Spring 表单处理

简介:

1. SimpleFormController vs @Controller

In XML-based Spring MVC web application, you create a form controller by extending the SimpleFormController class.

In annotation-based, you can use @Controller instead.

SimpleFormController

public class CustomerController extends SimpleFormController{
      //...
}

Annotation

@Controller
@RequestMapping("/customer.htm")
public class CustomerController{
      //...
}
 

2. formBackingObject() vs RequestMethod.GET

In SimpleFormController, you can initialize the command object for binding in the formBackingObject() method. In annotation-based, you can do the same by annotated the method name with @RequestMapping(method = RequestMethod.GET).

SimpleFormController

        @Override
	protected Object formBackingObject(HttpServletRequest request)
		throws Exception {
 
		Customer cust = new Customer();
		//Make "Spring MVC" as default checked value
		cust.setFavFramework(new String []{"Spring MVC"});
 
		return cust;
	}

Annotation

        @RequestMapping(method = RequestMethod.GET)
	public String initForm(ModelMap model){
 
		Customer cust = new Customer();
		//Make "Spring MVC" as default checked value
		cust.setFavFramework(new String []{"Spring MVC"});
 
		//command object
		model.addAttribute("customer", cust);
 
		//return form view
		return "CustomerForm";
	}

3. onSubmit() vs RequestMethod.POST

In SimpleFormController, the form submission is handle by the onSubmit() method. In annotation-based, you can do the same by annotated the method name with @RequestMapping(method = RequestMethod.POST).

SimpleFormController

       @Override
	protected ModelAndView onSubmit(HttpServletRequest request,
		HttpServletResponse response, Object command, BindException errors)
		throws Exception {
 
		Customer customer = (Customer)command;
		return new ModelAndView("CustomerSuccess");
 
	}

Annotation

	@RequestMapping(method = RequestMethod.POST)
	public String processSubmit(
		@ModelAttribute("customer") Customer customer,
		BindingResult result, SessionStatus status) {
 
		//clear the command object from the session
		status.setComplete(); 
 
		//return form success view
		return "CustomerSuccess";
 
	}

4. referenceData() vs @ModelAttribute

In SimpleFormController, usually you put the reference data in model via referenceData() method, so that the form view can access it. In annotation-based, you can do the same by annotated the method name with @ModelAttribute.

SimpleFormController

	@Override
	protected Map referenceData(HttpServletRequest request) throws Exception {
 
		Map referenceData = new HashMap();
 
		//Data referencing for web framework checkboxes
		List<String> webFrameworkList = new ArrayList<String>();
		webFrameworkList.add("Spring MVC");
		webFrameworkList.add("Struts 1");
		webFrameworkList.add("Struts 2");
		webFrameworkList.add("JSF");
		webFrameworkList.add("Apache Wicket");
		referenceData.put("webFrameworkList", webFrameworkList);
 
		return referenceData;
	}

Spring’s form

	<form:checkboxes items="${webFrameworkList}" path="favFramework" />

Annotation

	@ModelAttribute("webFrameworkList")
	public List<String> populateWebFrameworkList() {
 
		//Data referencing for web framework checkboxes
		List<String> webFrameworkList = new ArrayList<String>();
		webFrameworkList.add("Spring MVC");
		webFrameworkList.add("Struts 1");
		webFrameworkList.add("Struts 2");
		webFrameworkList.add("JSF");
		webFrameworkList.add("Apache Wicket");
 
		return webFrameworkList;
	}

Spring’s form

	<form:checkboxes items="${webFrameworkList}" path="favFramework" />

5. initBinder() vs @InitBinder

In SimpleFormController, you define the binding or register the custom property editor via initBinder() method. In annotation-based, you can do the same by annotated the method name with @InitBinder.

SimpleFormController

    protected void initBinder(HttpServletRequest request,
		ServletRequestDataBinder binder) throws Exception {
 
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

Annotation

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
 
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}

From Validation

In SimpleFormController, you have to register and map the validator class to the controller class via XML bean configuration file, and the validation checking and work flows will be executed automatically.

In annotation-based, you have to explicitly execute the validator and define the validation flow in the @Controller class manually. See the different :

SimpleFormController

	<bean class="com.mkyong.customer.controller.CustomerController">
                <property name="formView" value="CustomerForm" />
		<property name="successView" value="CustomerSuccess" />
 
		<!-- Map a validator -->
		<property name="validator">
			<bean class="com.mkyong.customer.validator.CustomerValidator" />
		</property>
	</bean>

Annotation

@Controller
@RequestMapping("/customer.htm")
public class CustomerController{
 
	CustomerValidator customerValidator;
 
	@Autowired
	public CustomerController(CustomerValidator customerValidator){
		this.customerValidator = customerValidator;
	}
 
	@RequestMapping(method = RequestMethod.POST)
	public String processSubmit(
		@ModelAttribute("customer") Customer customer,
		BindingResult result, SessionStatus status) {
 
		customerValidator.validate(customer, result);
 
		if (result.hasErrors()) {
			//if validator failed
			return "CustomerForm";
		} else {
			status.setComplete();
			//form success
			return "CustomerSuccess";
		}
	}
	//...

Full Example

See a complete @Controller example.

package com.mkyong.customer.controller;
 
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
 
import com.mkyong.customer.model.Customer;
import com.mkyong.customer.validator.CustomerValidator;
 
@Controller
@RequestMapping("/customer.htm")
public class CustomerController{
 
	CustomerValidator customerValidator;
 
	@Autowired
	public CustomerController(CustomerValidator customerValidator){
		this.customerValidator = customerValidator;
	}
 
	@RequestMapping(method = RequestMethod.POST)
	public String processSubmit(
		@ModelAttribute("customer") Customer customer,
		BindingResult result, SessionStatus status) {
 
		customerValidator.validate(customer, result);
 
		if (result.hasErrors()) {
			//if validator failed
			return "CustomerForm";
		} else {
			status.setComplete();
			//form success
			return "CustomerSuccess";
		}
	}
 
	@RequestMapping(method = RequestMethod.GET)
	public String initForm(ModelMap model){
 
		Customer cust = new Customer();
		//Make "Spring MVC" as default checked value
		cust.setFavFramework(new String []{"Spring MVC"});
 
		//Make "Make" as default radio button selected value
		cust.setSex("M");
 
		//make "Hibernate" as the default java skills selection
		cust.setJavaSkills("Hibernate");
 
		//initilize a hidden value
		cust.setSecretValue("I'm hidden value");
 
		//command object
		model.addAttribute("customer", cust);
 
		//return form view
		return "CustomerForm";
	}
 
 
	@ModelAttribute("webFrameworkList")
	public List<String> populateWebFrameworkList() {
 
		//Data referencing for web framework checkboxes
		List<String> webFrameworkList = new ArrayList<String>();
		webFrameworkList.add("Spring MVC");
		webFrameworkList.add("Struts 1");
		webFrameworkList.add("Struts 2");
		webFrameworkList.add("JSF");
		webFrameworkList.add("Apache Wicket");
 
		return webFrameworkList;
	}
 
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
 
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
 
	}
 
	@ModelAttribute("numberList")
	public List<String> populateNumberList() {
 
		//Data referencing for number radiobuttons
		List<String> numberList = new ArrayList<String>();
		numberList.add("Number 1");
		numberList.add("Number 2");
		numberList.add("Number 3");
		numberList.add("Number 4");
		numberList.add("Number 5");
 
		return numberList;
	}
 
	@ModelAttribute("javaSkillsList")
	public Map<String,String> populateJavaSkillList() {
 
		//Data referencing for java skills list box
		Map<String,String> javaSkill = new LinkedHashMap<String,String>();
		javaSkill.put("Hibernate", "Hibernate");
		javaSkill.put("Spring", "Spring");
		javaSkill.put("Apache Wicket", "Apache Wicket");
		javaSkill.put("Struts", "Struts");
 
		return javaSkill;
	}
 
	@ModelAttribute("countryList")
	public Map<String,String> populateCountryList() {
 
		//Data referencing for java skills list box
		Map<String,String> country = new LinkedHashMap<String,String>();
		country.put("US", "United Stated");
		country.put("CHINA", "China");
		country.put("SG", "Singapore");
		country.put("MY", "Malaysia");
 
		return country;
	}
}

To make annotation work, you have to enable the component auto scanning feature in Spring.

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-2.5.xsd">
 
	<context:component-scan base-package="com.mkyong.customer.controller" />
 
	<bean class="com.mkyong.customer.validator.CustomerValidator" />
 
 	<!-- Register the Customer.properties -->
	<bean id="messageSource"
		class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basename" value="com/mkyong/customer/properties/Customer" />
	</bean>
 
	<bean id="viewResolver"
	      class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
              <property name="prefix">
                 <value>/WEB-INF/pages/</value>
              </property>
              <property name="suffix">
                 <value>.jsp</value>
              </property>
        </bean>
</beans>

Download Source Code


==============================================================================
本文转自被遗忘的博客园博客,原文链接:http://www.cnblogs.com/rollenholt/archive/2012/12/27/2836249.html,如需转载请自行联系原作者
相关文章
|
5月前
|
前端开发 Java Spring
Spring MVC拦截器+注解方式实现防止表单重复提交
Spring MVC拦截器+注解方式实现防止表单重复提交
|
6月前
|
JSON Java PHP
Spring Boot 一个接口同时支持 form 表单、form-data、json 优雅写法
网上很多代码都是千篇一律的 cvs,相信我只要你认真看完我写的这篇,你就可以完全掌握这个知识点,这篇文章不适合直接 cvs,一定要先理解。
|
4月前
|
存储 前端开发 Java
Spring Boot中Spring MVC的表单标签库与数据绑定讲解与实战(附源码 超详细必看)
Spring Boot中Spring MVC的表单标签库与数据绑定讲解与实战(附源码 超详细必看)
33 0
|
8月前
|
存储 安全 Java
Spring Security-2-表单认证
我们在地址小节介绍了Spring Security的HttpBasic基础认证模式,这个模式方法比较简单,不需要制作登录页面,使用范围较小。如果我们在一个完整的系统里面,登录页面也许我们自己设计,并且提供多种登录方式。这就需要使用Spring Security为我们提供的表单登录进行登录认证
75 0
|
安全 前端开发 Java
Spring Security系列教程05--实现Form表单认证
前言 在上一章节中,一一哥 带大家认识了Spring Security中的第一种认证方式,但是这种基本认证的方式,UI效果不漂亮,安全性也很差,好像一无是处的样子,那么有没有更好一点的认证方式呢?有的!接下来我给大家介绍一个新的认证方式,即Form表单认证。 一. Form表单认证 1. 认证方式 我们从前文中得知,Spring Security中的认证方式可以分为HTTP层面和表单层面,常见的认证方式如下: • ①. HTTP基本认证; • ②. Form表单认证; • ③. HTTP摘要认证;
409 0
|
12月前
|
存储 JSON 安全
手摸手教你定制 Spring Security 表单登录
手摸手教你定制 Spring Security 表单登录
|
安全 前端开发 Oracle
Spring Security表单登录认证
Spring Security是一个强有力并且高度定制化的认证和访问控制框架,致力于为Java应用程序提供认证和授权。
Spring Security表单登录认证
|
前端开发 Java Spring
Spring MVC框架:第八章:表单form:form标签
Spring MVC框架:第八章:表单form:form标签
163 0
Spring MVC框架:第八章:表单form:form标签
|
JSON 前端开发 Java
Spring MVC 实战:复杂类型接收表单字段
前言 这是 Spring MVC 处理器方法参数实战的第二篇,我们来尝试使用复杂的成员变量类型来接收 form 表单字段。 对于普通的 Java Web 项目,我们一般通过 ServletRequest#getParameter 方法来获取字符串类型的 form 表单字段值。
181 0
Spring MVC 实战:复杂类型接收表单字段
|
前端开发 Java Spring
Spring MVC表单防重复提交
利用Spring MVC的过滤器及token传递验证来实现表单防重复提交。 创建注解
138 0