springMvc 数据绑定,类型转换,数据校验 解析
2016-09-29 00:00
801 查看
springMvc 数据绑定,类型转换,数据校验 解析
解决的办法就是使用spring mvc提供的@InitBinder标签
在我的项目中是在BaseController中增加方法initBinder,并使用注解@InitBinder标注,那么spring mvc在绑定表单之前,都会先注册这些编辑器,当然你如果不嫌麻烦,你也可以单独的写在你的每一个controller中。剩下的控制器都继承该类。spring自己提供了大量的实现类,诸如CustomDateEditor ,CustomBooleanEditor,CustomNumberEditor等许多,基本上够用。
自定义写法:
BaseController
IntegerEditor
更多配置,请下载本实例源码
StoreController
jsp
结果
将此转换器在mvc配置文件中注册
如果使用的是默认的<mvc:annotation-driven/>来注册的adapter,那么久不需要上面的配置,直接在其中配置converterService属性即可
如果在上述注册了FormattingConversionServiceFactoryBean或者是ConversionServiceFactoryBean,就可以在entity中的属性中使用注解来进行数据绑定了
数据绑定
注解InitBinder实现数据绑定
在SpringMVC中,bean中定义了Date,double等类型,如果没有做任何处理的话,日期以及double都无法绑定。解决的办法就是使用spring mvc提供的@InitBinder标签
在我的项目中是在BaseController中增加方法initBinder,并使用注解@InitBinder标注,那么spring mvc在绑定表单之前,都会先注册这些编辑器,当然你如果不嫌麻烦,你也可以单独的写在你的每一个controller中。剩下的控制器都继承该类。spring自己提供了大量的实现类,诸如CustomDateEditor ,CustomBooleanEditor,CustomNumberEditor等许多,基本上够用。
自定义写法:
BaseController
package com.zefun.web.controller; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.stereotype.Controller; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import com.zefun.web.editor.DoubleEditor; import com.zefun.web.editor.FloatEditor; import com.zefun.web.editor.IntegerEditor; import com.zefun.web.editor.LongEditor; @Controller public class BaseController { @InitBinder protected void initBinder(WebDataBinder binder) { binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true)); binder.registerCustomEditor(int.class, new IntegerEditor()); binder.registerCustomEditor(long.class, new LongEditor()); binder.registerCustomEditor(double.class, new DoubleEditor()); binder.registerCustomEditor(float.class, new FloatEditor()); //下面是spring自定义提供的 //binder.registerCustomEditor(int.class, new CustomNumberEditor(int.class, true)); //binder.registerCustomEditor(long.class, new CustomNumberEditor(long.class, true)); } }
IntegerEditor
package com.zefun.web.editor; import org.springframework.beans.propertyeditors.PropertiesEditor; public class IntegerEditor extends PropertiesEditor { @Override public void setAsText(String text) throws IllegalArgumentException { if (text == null || text.equals("")) { text = "0"; } setValue(Integer.parseInt(text)); } @Override public String getAsText() { return getValue().toString(); } }
更多配置,请下载本实例源码
StoreController
package com.zefun.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.zefun.common.consts.Url; import com.zefun.web.dto.BaseDto; import com.zefun.web.entity.StoreInfo; @Controller public class StoreInfoController extends BaseController{ @RequestMapping(value = Url.StoreInfo.actionSave, method = RequestMethod.POST) @ResponseBody public BaseDto actionSave(StoreInfo storeInfo){ System.out.println(storeInfo.toString()); System.out.println(storeInfo.getDate()); return new BaseDto(0, "fail"); } }
jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path + "/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <script type="text/javascript" src="<%=basePath %>js/ajax.js"></script> <script type="text/javascript" src="<%=basePath %>js/jquery-1.9.1.min.js"></script> <body> <div> <input type="text" name="date"> <input type="text" name="id"> <input type="button" value="数据绑定" onclick="initBuild()"> </div> function initBuild(){ var date = jQuery("input[name='date']").val(); var id = jQuery("input[name='id']").val(); jQuery.ajax({ url: baseUrl+"store/action/save", data: "date="+date+"&id="+id, type:"POST", success: function(data) { console.log(data.msg); } }); } </script> </body> </html>
结果
StoreInfo [date=Wed Dec 12 00:00:00 CST 1990, id=4] Wed Dec 12 00:00:00 CST 1990
配置converter实现数据绑定
集成converter接口进行重写转换器package com.zefun.web.converter; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; import com.zefun.web.entity.Employee; /** * 1.自定义类型转换器,比如在表单中请求epms的时候 ,提交的数据格式是//GG-gg@atguigu.com-0-105 * 就会返回一个Employee类型的bean,而在请求的方法参数中这样写(@RequestParam(value="表单name") Employee employee) * 在强制转换的时候就会使用该转换器 * 2.配置转换器 在xml中有详细讲解 */ @Component(value="employeeConverter") public class EmployeeConverter implements Converter<String, Employee> { public Employee convert(String source) { if (source != null) { String[] vals = source.split("-"); // GG-gg@atguigu.com-0-105 if (vals != null && vals.length == 4) { String lastName = vals[0]; String email = vals[1]; Integer gender = Integer.parseInt(vals[2]); Employee employee = new Employee(null, lastName, email, gender); System.out.println(source + "--convert--" + employee); return employee; } } return null; } }
将此转换器在mvc配置文件中注册
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name= "webBindingInitializer" ref= "webBindingInitializer"/> </bean> <bean id= "conversionService" class= "org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name= "converters"> <list> <bean class= "com.zefun.web.converter.EmployeeConverter"/> </list> </property> </bean> <bean id= "webBindingInitializer" class= "org.springframework.web.bind.support.ConfigurableWebBindingInitializer"> <property name= "conversionService" ref= "conversionService"/> </bean>
如果使用的是默认的<mvc:annotation-driven/>来注册的adapter,那么久不需要上面的配置,直接在其中配置converterService属性即可
<mvc:annotation-driven conversion-service="conversionService"/> <bean id= "conversionService" class= "com.zefun.web.converter.EmployeeConverter"></bean>
如果在上述注册了FormattingConversionServiceFactoryBean或者是ConversionServiceFactoryBean,就可以在entity中的属性中使用注解来进行数据绑定了
@DateTimeFormat(pattern="yyyy-MM-dd") private Date birth; @NumberFormat(pattern="#,###,###.#") private Float salary;
相关文章推荐
- springMvc 数据绑定,类型转换,数据校验 解析
- springMvc 数据绑定,类型转换,数据校验 解析
- 【SpringMVC】SpringMVC系列12之数据类型转换、格式化、校验
- SpringMVC类型转换、数据绑定详解[附带源码分析]
- SpringMVC类型转换、数据绑定
- 6.校验,数据绑定和类型转换(6.1 - 6.3)
- SpringMVC-8 数据类型转换、数据格式化与数据校验
- Springmvc学习笔记(4)之复杂参数类型绑定、校验、数据回显和异常处理
- SpringMVC类型转换、数据绑定详解
- SpringMVC类型转换、数据绑定
- SpringMVC 类型转换、数据绑定
- SpringMVC类型转换、数据绑定详解
- springMVC对简单对象,Set,List,Map的数据绑定及类型转换
- springMVC数据绑定、类型转换
- springMVC与MyBatis中绑定枚举类型数据的转换
- 框架学习之springMvc整合框架-03数据校验、类型转换
- SpringMVC类型转换、数据绑定详解[附带源码分析]
- SpringMVC——类型转换和格式化、数据校验、客户端显示错误消息
- SpringMVC数据类型转换—— 注解式控制器的数据验证、类型转换及格式化
- springMVC学习笔记四(数据类型转换和数据验证)