总共方法有三种:
第一种:繁重操作解决方式:
在 Controller 里面不写 InitBinder 方法; 直接在请求实体类里面将DATE 类型的字段 注解
@DateTimeFormat("格式")
第二种:比较繁重操作解决方式:
在 Controller 里面写 InitBinder 方法; 里面写多个日期格式;将特殊的标出;如下代码:
@InitBinder public void initBinder(WebDataBinder b) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); b.registerCustomEditor(Date.class, new CustomDateEditor(df, true)); DateFormat df2 = new SimpleDateFormat("yyyy-MM"); String[] fileds = {"字段名", "字段名", "字段名"}; for(String filed : fileds){ b.registerCustomEditor(Date.class, filed, new CustomDateEditor(df2, true)); } }
第三种:轻松解决方式:
自己写一个DATE数据绑定类;然后在Controller 里面写 InitBinder 方法里面应用;如下代码
package com.luwen.dai.util; import java.beans.PropertyEditorSupport; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SpecialDateEditor extends PropertyEditorSupport { private final Logger logger = LoggerFactory.getLogger(getClass()); @Override public void setAsText(String text) throws IllegalArgumentException { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = null; try { //防止空数据出错 if(StringUtils.isNotBlank(text)){ date = format.parse(text); } } catch (ParseException e) { format = new SimpleDateFormat("yyyy-MM-dd"); try { date = format.parse(text); } catch (ParseException e1) { format = new SimpleDateFormat("yyyy-MM"); try{ date = format.parse(text); }catch (Exception e2) { logger.error("自动绑定日期数据出错", e); } } } setValue(date); } }
然后在initBinder 方法里直接引用
@InitBinder public void initBinder(WebDataBinder b) { b.registerCustomEditor(Date.class, new SpecialDateEditor()); }
相关推荐
spring 属性参考与自动绑定.txt
NULL 博文链接:https://yfm049.iteye.com/blog/860494
spring MVC数据绑定 含例子 转载自疯芒毕露的专栏 刚开始用spring mvc 做web开发时 经常会不知道如何合适绑定页面数据 用惯struts2的朋友更认为spring mvc 绑定数据不如struts2方便 本人最开始也是这么认为 经过一段...
spring数据绑定课程,适合新手学习,包含了 简单的数据类型,POJO数据绑定,字符编码的修复,各类问题的解释
(3)byType:根据属性 类型 自动装配,相同类型多个会抛出异常,设值注入 <bean class="xxx" ></bean> (4)constructor:与 byType 方式类似,不同之处是构造注入 <bean class="xxx" ></bean> 本例,演示 byName...
spring数据绑定.docx
spring自动加载缓存
本项目为Java项目,使用Spring实现自动装配,根据类型方式实现自动装配。适合初学者了解Spring不同装配方式。
Spring+MVC数据绑定大全+
资源名称:Spring Framework开发参考手册 chm格式 内容简介: Spring Framework 开发手册 chm,一份对Spring特性的参考指南,内容涵盖Spring概述、使用场景、Spring2.0新特性、面向切面编程、中间层...
自己写的spring表单绑定的小例子,分别使用SimpleFormController,MultiActionController,spring的form tag和validator。 还在MultiActionController里面实现了表单的绑定
Spring自动装配解析,具体效果和过程看博文 http://blog.csdn.net/evankaka/article/details/44836069
NULL 博文链接:https://kanpiaoxue.iteye.com/blog/2164464
第12章Spring MVC参数绑定的验证 简单数据类型绑定 默认数据类型绑定 POJO类型 复杂数据类型绑定(数组、集合)
在myeclipse自动提示spring的配置信息
spring自动装配项目struts2,使用了struts2 ,spring2.5 ,hibernate,和spring 自动装配
spring的自动装配
spring自动扫描和管理Bean的示例
Spring整合Spring Data JPA 的使用,包括三种的查询方式 借助接口中的定义好的方法完成查询 jpql的查询方式 方法名称规则查询
JavaEE spring半自动实现AOP代理