Spring MVC表单处理注释示例

在本教程中,我们向您展示如何通过在Spring MVC Web应用程序中使用注释来进行表单处理。

注意
这个基于注释的示例是从最后一个基于XML的 Spring MVC 表单处理示例转换而来的。 因此,请比较并找出不同之处。

1. SimpleFormController与@Controller

在基于XML的Spring MVC Web应用程序中,您可以通过扩展SimpleFormController类来创建表单控制器。

在基于注释的情况下,可以改用@Controller

SimpleFormController

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

注解

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

2. formBackingObject()与RequestMethod.GET

在SimpleFormController中,您可以在formBackingObject()方法中初始化要绑定的命令对象。 在基于注释的方法中,可以通过使用@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;
	}

注解

@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()与RequestMethod.POST

在SimpleFormController中,表单提交由onSubmit()方法处理。 在基于注释的方法中,可以通过使用@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");
 
	}

注解

@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()与@ModelAttribute

在SimpleFormController中,通常可以通过referenceData()方法将参考数据放入模型中,以便表单视图可以访问它。 在基于注释的方法中,可以通过使用@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;
	}

春天的形式

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

注解

@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;
	}

春天的形式

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

5. initBinder()与@InitBinder

在SimpleFormController中,您可以定义绑定或通过initBinder()方法注册自定义属性编辑器。 在基于注释的方法中,可以通过使用@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));
    }

注解

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

从验证

在SimpleFormController中,您必须通过XML bean配置文件注册验证器类并将其映射到控制器类,验证检查和工作流程将自动执行。

在基于注释的情况下,您必须显式执行验证器并在@Controller类中手动定义验证流程。 看到不同的:

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>

注解

@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";
		}
	}
	//...

完整的例子

请参阅完整的@Controller示例。

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;
	}
}

要使注释生效,您必须在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>

下载源代码

下载它– SpringMVC-Form-Handling-Annotation-Example.zip (12KB)

参考

  1. Spring 2.5中带注释的Web MVC控制器
  2. Spring MVC表单处理示例– XML版本
  3. Spring MVC Hello World注释示例
  4. Spring MVC MultiActionController注释示例

翻译自: https://mkyong.com/spring-mvc/spring-mvc-form-handling-annotation-example/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值