springMvc 数据绑定,类型转换,数据校验 解析

springMvc 数据绑定,类型转换,数据校验 解析


数据绑定

注解InitBinder实现数据绑定

在SpringMVC中,bean中定义了Date,double等类型,如果没有做任何处理的话,日期以及double都无法绑定。

解决的办法就是使用spring mvc提供的@InitBinder标签

在我的项目中是在BaseController中增加方法initBinder,并使用注解@InitBinder标注,那么spring mvc在绑定表单之前,都会先注册这些编辑器,当然你如果不嫌麻烦,你也可以单独的写在你的每一个controller中。剩下的控制器都继承该类。spring自己提供了大量的实现类,诸如CustomDateEditor ,CustomBooleanEditor,CustomNumberEditor等许多,基本上够用。


自定义写法:

BaseController

  1. package com.zefun.web.controller;  
  2.   
  3. import java.text.SimpleDateFormat;  
  4. import java.util.Date;  
  5.   
  6. import org.springframework.beans.propertyeditors.CustomDateEditor;  
  7. import org.springframework.stereotype.Controller;  
  8. import org.springframework.web.bind.WebDataBinder;  
  9. import org.springframework.web.bind.annotation.InitBinder;  
  10.   
  11. import com.zefun.web.editor.DoubleEditor;  
  12. import com.zefun.web.editor.FloatEditor;  
  13. import com.zefun.web.editor.IntegerEditor;  
  14. import com.zefun.web.editor.LongEditor;  
  15.   
  16. @Controller  
  17. public class BaseController {  
  18.       
  19.     @InitBinder    
  20.     protected void initBinder(WebDataBinder binder) {    
  21.         binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));    
  22.         binder.registerCustomEditor(int.class, new IntegerEditor());    
  23.         binder.registerCustomEditor(long.class, new LongEditor());    
  24.         binder.registerCustomEditor(double.class, new DoubleEditor());    
  25.         binder.registerCustomEditor(float.class, new FloatEditor());    
  26.         //下面是spring自定义提供的  
  27.         //binder.registerCustomEditor(int.class, new CustomNumberEditor(int.class, true));  
  28.         //binder.registerCustomEditor(long.class, new CustomNumberEditor(long.class, true));   
  29.     }   
  30.       
  31. }  

IntegerEditor

  1. package com.zefun.web.editor;  
  2.   
  3. import org.springframework.beans.propertyeditors.PropertiesEditor;  
  4.   
  5. public class IntegerEditor extends PropertiesEditor {    
  6.     @Override    
  7.     public void setAsText(String text) throws IllegalArgumentException {    
  8.         if (text == null || text.equals("")) {    
  9.             text = "0";    
  10.         }    
  11.         setValue(Integer.parseInt(text));    
  12.     }    
  13.     
  14.     @Override    
  15.     public String getAsText() {    
  16.         return getValue().toString();    
  17.     }    
  18. }   

更多配置,请下载本实例源码

StoreController

  1. package com.zefun.web.controller;  
  2.   
  3. import org.springframework.stereotype.Controller;  
  4. import org.springframework.web.bind.annotation.RequestMapping;  
  5. import org.springframework.web.bind.annotation.RequestMethod;  
  6. import org.springframework.web.bind.annotation.ResponseBody;  
  7. import org.springframework.web.servlet.ModelAndView;  
  8.   
  9. import com.zefun.common.consts.Url;  
  10. import com.zefun.web.dto.BaseDto;  
  11. import com.zefun.web.entity.StoreInfo;  
  12.   
  13. @Controller  
  14. public class StoreInfoController extends BaseController{  
  15.       
  16.       
  17.     @RequestMapping(value = Url.StoreInfo.actionSave, method = RequestMethod.POST)  
  18.     @ResponseBody  
  19.     public BaseDto actionSave(StoreInfo storeInfo){  
  20.         System.out.println(storeInfo.toString());  
  21.         System.out.println(storeInfo.getDate());  
  22.         return new BaseDto(0, "fail");  
  23.     }  
  24.   
  25. }  

jsp

  1. <%@ page language="java" contentType="text/html; charset=utf-8"  
  2.     pageEncoding="utf-8"%>  
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path + "/";  
  6. %>  
  7. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  8. <html>  
  9. <head>  
  10. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
  11. <title>Insert title here</title>  
  12. </head>  
  13. <script type="text/javascript" src="<%=basePath %>js/ajax.js"></script>  
  14. <script type="text/javascript" src="<%=basePath %>js/jquery-1.9.1.min.js"></script>  
  15. <body>  
  16. <div>  
  17. <input type="text" name="date">  
  18. <input type="text" name="id">  
  19. <input type="button" value="数据绑定" onclick="initBuild()">  
  20. </div>  
  21.   
  22. function initBuild(){  
  23.     var date = jQuery("input[name='date']").val();  
  24.     var id = jQuery("input[name='id']").val();  
  25.     jQuery.ajax({  
  26.         url: baseUrl+"store/action/save",  
  27.         data: "date="+date+"&id="+id,  
  28.         type:"POST",  
  29.         success: function(data) {  
  30.            console.log(data.msg);  
  31.         }  
  32.     });  
  33. }  
  34. </script>  
  35. </body>  
  36. </html>  

结果

  1. StoreInfo [date=Wed Dec 12 00:00:00 CST 1990, id=4]  
  2. Wed Dec 12 00:00:00 CST 1990  

配置converter实现数据绑定

集成converter接口进行重写转换器

  1. package com.zefun.web.converter;  
  2.   
  3. import org.springframework.core.convert.converter.Converter;  
  4. import org.springframework.stereotype.Component;  
  5.   
  6. import com.zefun.web.entity.Employee;  
  7.   
  8. /**  
  9.  * 1.自定义类型转换器,比如在表单中请求epms的时候 ,提交的数据格式是//GG-gg@atguigu.com-0-105  
  10.  *      就会返回一个Employee类型的bean,而在请求的方法参数中这样写(@RequestParam(value="表单name") Employee employee)  
  11.  *      在强制转换的时候就会使用该转换器  
  12.  * 2.配置转换器 在xml中有详细讲解  
  13.  */  
  14. @Component(value="employeeConverter")  
  15. public class EmployeeConverter implements Converter<String, Employee> {  
  16.   
  17.     public Employee convert(String source) {  
  18.         if (source != null) {  
  19.             String[] vals = source.split("-");  
  20.             // GG-gg@atguigu.com-0-105  
  21.             if (vals != null && vals.length == 4) {  
  22.                 String lastName = vals[0];  
  23.                 String email = vals[1];  
  24.                 Integer gender = Integer.parseInt(vals[2]);  
  25.                 Employee employee = new Employee(null, lastName, email, gender);  
  26.                 System.out.println(source + "--convert--" + employee);  
  27.                 return employee;  
  28.             }  
  29.         }  
  30.         return null;  
  31.     }  
  32.   
  33. }  

将此转换器在mvc配置文件中注册

  1. <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">  
  2.     <property name"webBindingInitializer" ref"webBindingInitializer"/>  
  3. </bean>  
  4. <bean id"conversionService" class"org.springframework.format.support.FormattingConversionServiceFactoryBean">  
  5.     <property name"converters">  
  6.        <list>  
  7.         <bean class"com.zefun.web.converter.EmployeeConverter"/>  
  8.         </list>  
  9.     </property>  
  10. </bean>  
  11.   
  12. <bean id"webBindingInitializer" class"org.springframework.web.bind.support.ConfigurableWebBindingInitializer">  
  13.     <property name"conversionService" ref"conversionService"/>  
  14. </bean>  

如果使用的是默认的<mvc:annotation-driven/>来注册的adapter,那么久不需要上面的配置,直接在其中配置converterService属性即可
  1. <mvc:annotation-driven conversion-service="conversionService"/>  
  2. <bean id"conversionService" class"com.zefun.web.converter.EmployeeConverter"></bean>  

如果在上述注册了FormattingConversionServiceFactoryBean或者是ConversionServiceFactoryBean,就可以在entity中的属性中使用注解来进行数据绑定了
  1. @DateTimeFormat(pattern="yyyy-MM-dd")  
  2. private Date birth;  
  3.   
  4. @NumberFormat(pattern="#,###,###.#")  
  5. private Float salary; 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值