Spring MVC 参数依赖注入时,String参数注入为Date类型
来源:互联网 发布:linux用户和组管理命令 编辑:程序博客网 时间:2024/05/22 12:47
在Controller里面增加:
@InitBinderprotected void initBinder(HttpServletRequest request,ServletRequestDataBinder binder) throws Exception {// 对于需要转换为Date类型的属性,使用DateEditor进行处理binder.registerCustomEditor(Date.class, new SpringBindDateEditor());}
public class SpringBindDateEditor extends PropertyEditorSupport {Logger logger=Logger.getLogger(SpringBindDateEditor.class); private static final DateFormat DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd"); private static final DateFormat TIMEFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm"); public static void main(String[] args) throws Exception { System.out.println(TIMEFORMAT.parse("2014-10-30 23:50"));;} private DateFormat dateFormat; private boolean allowEmpty = true; public SpringBindDateEditor() { } public SpringBindDateEditor(DateFormat dateFormat) { this.dateFormat = dateFormat; } public SpringBindDateEditor(DateFormat dateFormat, boolean allowEmpty) { this.dateFormat = dateFormat; this.allowEmpty = allowEmpty; } /** * Parse the Date from the given text, using the specified DateFormat. */ @Override public void setAsText(String text) throws IllegalArgumentException { System.out.println(text); if (this.allowEmpty && !org.apache.commons.lang3.StringUtils.isNotEmpty(text)) { // Treat empty String as null value. setValue(null); } else { try { if(this.dateFormat != null) setValue(this.dateFormat.parse(text)); else { if(text.contains(":")){ System.out.println("格式化!"+text); Date date=TIMEFORMAT.parse(text); System.out.println("Passed "); setValue(date); } else setValue(DATEFORMAT.parse(text)); } } catch (ParseException ex) { logger.error("绑定时间出错"+text); throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex); } } } /** * Format the Date as String, using the specified DateFormat. */ @Override public String getAsText() { Date value = (Date) getValue(); DateFormat dateFormat = this.dateFormat; if(dateFormat == null) dateFormat = TIMEFORMAT; return (value != null ? dateFormat.format(value) : ""); }}
0 0
- Spring MVC 参数依赖注入时,String参数注入为Date类型
- spring注入class类型参数
- Spring装配bean,依赖注入及注入参数
- Spring依赖注入类型
- Spring MVC 自定义方法参数注入
- spring注入枚举类型作为参数
- spring 注入枚举类型作为参数
- Spring-注入参数详解-[集合类型属性]
- Spring依赖注入对于Date类型数据的处理
- Spring mvc Date类型参数为空时,controller报错
- 没有为该对象定义无参数的构造函数(MVC 之DefaultControllerFactory 依赖注入)
- Spring DI 依赖注入案例(带参数构造方法依赖注入、setter方法依赖注入、p名称空间注入)
- Spring MVC学习--依赖注入
- spring 注入参数
- spring参数注入细节
- 004. Spring 注入参数
- Spring 参数注入方法
- 依赖注入的参数详解
- 整理hibernate.cfg.xml 与 applicationContext之间的配置方式
- windows命令行问题
- Oracle数据库备份、恢复 - 使用PL/SQL Developer 导入、导出Oracle数据库
- js echo中对像转成字符串
- SQL2008,SQL2005存储过程解密
- Spring MVC 参数依赖注入时,String参数注入为Date类型
- Registry Settings that can be Modified to Improve Operating System Performance
- app测试点
- 关于在链表中用递归形式,求出链表中的最大值,及节点数和平均值的函数
- Thrift框架介绍
- javascrpit 执行字符串指令
- codeforces571A. Lengthening Sticks
- Android封装TextView内容伸缩工具
- Oracle 生成合并行报表