Spring MVC框架下提交Date数据无法在controller直接接收
主要有两步,controller中添加initBinder方法,再创建一个时间类型数据转换类就OK了。
1、在Controller中创建方法:
// 相关包 import java.text.DateFormat; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.web.bind.ServletRequestDataBinder; // 方法 @InitBinder protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { DateFormat df = new MyDateFormat("yyyy-MM-dd HH:mm:ss"); CustomDateEditor editor = new CustomDateEditor(df, false); binder.registerCustomEditor(Date.class, editor); }
例如:
@Controller public class MyController {
@InitBinder protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { DateFormat df = new MyDateFormat("yyyy-MM-dd HH:mm:ss"); CustomDateEditor editor = new CustomDateEditor(df, false); binder.registerCustomEditor(Date.class, editor); } // 省略 }
2、创建日期类:MyDateFormat
package com.common.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class MyDateFormat extends SimpleDateFormat { private static final long serialVersionUID = 2371168145105228746L; private String[] patterns = new String[] { "yyyyMMdd", "yyyy-MM-dd HH:mm", "HH:mm", "yyyy-MM-dd" }; public Date parse(String source) throws ParseException { try { if (source == null) source = ""; if (toPattern().length() == source.length()) return super.parse(source); for (int i = 0; i < patterns.length; i++) { if (patterns[i].length() == source.length()) { applyPattern(patterns[i]); return super.parse(source); } } return null; } catch (Exception e) { e.printStackTrace(); return null; } } public MyDateFormat() { super(); } public MyDateFormat(String pattern) { super(pattern); } }
come on ,欢迎讨论;