首页 文章 精选 留言 我的

精选列表

搜索[表单验证],共10009篇文章
优秀的个人博客,低调大师

Spring 表单处理

1. SimpleFormController vs @Controller In XML-based Spring MVC web application, you create a form controller by extending theSimpleFormControllerclass. In annotation-based, you can use@Controllerinstead. 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 theformBackingObject()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 theonSubmit()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 viareferenceData()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 viainitBinder()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@Controllerclass 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 Download it – SpringMVC-Form-Handling-Annotation-Example.zip(12KB) ============================================================================== 本文转自被遗忘的博客园博客,原文链接:http://www.cnblogs.com/rollenholt/archive/2012/12/27/2836249.html,如需转载请自行联系原作者

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

WebStorm

WebStorm

WebStorm 是jetbrains公司旗下一款JavaScript 开发工具。目前已经被广大中国JS开发者誉为“Web前端开发神器”、“最强大的HTML5编辑器”、“最智能的JavaScript IDE”等。与IntelliJ IDEA同源,继承了IntelliJ IDEA强大的JS部分的功能。

用户登录
用户注册