springMvc 数据绑定,类型转换,数据校验 解析
来源:互联网 发布:php开发教程视频 编辑:程序博客网 时间:2024/09/21 08:58
springMvc 数据绑定,类型转换,数据校验 解析
数据绑定
注解InitBinder实现数据绑定
在SpringMVC中,bean中定义了Date,double等类型,如果没有做任何处理的话,日期以及double都无法绑定。
解决的办法就是使用spring mvc提供的@InitBinder标签
在我的项目中是在BaseController中增加方法initBinder,并使用注解@InitBinder标注,那么spring mvc在绑定表单之前,都会先注册这些编辑器,当然你如果不嫌麻烦,你也可以单独的写在你的每一个controller中。剩下的控制器都继承该类。spring自己提供了大量的实现类,诸如CustomDateEditor ,CustomBooleanEditor,CustomNumberEditor等许多,基本上够用。
解决的办法就是使用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;
0 0
- springMvc 数据绑定,类型转换,数据校验 解析
- springMvc 数据绑定,类型转换,数据校验 解析
- springMVC数据绑定、类型转换
- springMVC类型转换和数据绑定
- SpringMVC类型转换、数据绑定详解
- 6.校验,数据绑定和类型转换(6.1 - 6.3)
- SpringMVC类型转换、数据绑定详解[附带源码分析]
- springMVC与MyBatis中绑定枚举类型数据的转换
- 学习SpringMVC——数据绑定和类型转换
- SpringMVC类型转换、数据绑定详解[附带源码分析]
- springmvc 绑定枚举类型数据
- springmvc 绑定枚举类型数据
- 类型转换、数据校验、国际化
- Spring 框架参考文档(三)之数据校验、数据绑定和类型转换
- springmvc笔记-6-数据转换,格式化,校验
- SpringMVC--数据转换、格式化和校验
- springmvc知识四------数据转换&数据格式化&数据校验
- SpringMVC ----数据进行类型转换
- HTML遇到的问题
- 拿糖果
- linux
- chrome插件--jsonview安装
- 多态(1)静态多态与动态多态
- springMvc 数据绑定,类型转换,数据校验 解析
- 浅谈Html5的优势和劣势
- HDOJ 2824 The Euler function (欧拉函数)
- spring MVC中定义异常页面
- c++无限输入求和,非数组
- 委托,lambda表达式和事件
- spring boot-jpa整合QueryDSL来简化复杂操作
- bzoj 1036: [ZJOI2008]树的统计Count
- LeetCode 38. Count and Say 字符串“阅读式”扩张