在springmvc框架里有的时候是实体类接收的数据里面有特殊类型例如Date类型
直接放到你自己Controller层就可以(这样date类型的字段就能接收到数据)
@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
==================================以下是@InitBinder部分介绍和原文出处================
我们在接收参数的时候,对于基础的数据类型,比如接收string,int等类型,springmvc是可以直接处理的,但是对于其他复杂的对象类型,有时候是无法处理的,这时候就需要属性编辑器来进行处理(源数据为string),过程一般就是String->属性编辑器->目标类型。spring为我们提供了一些默认的属性编辑器,如org.springframework.beans.propertyeditors.CustomDateEditor就是其中一个,我们也可以通过继承java.beans.PropertyEditorSuppotr来根据具体的业务来定义自己的属性编辑器。
定义controller并使用@InitBinder注册属性编辑器
这里注册的属性编辑器为org.springframework.beans.propertybeans.CustomDateEditor,作用是根据提供的java.text.SimpleDateFormat将输入的字符串数据转换为java.util.Date类型的数据,核心源码如下:
org.springframework.beans.propertyeditors.CustomDateEditor#setAsText
public void setAsText(@Nullable String text) throws IllegalArgumentException {
...
else {
try {
// 使用用户提供的java.text.SimpeDateFormat来将目标字符串格式化为java.util.Date类型,并通过SetValue方法设置最终值
setValue(this.dateFormat.parse(text));
}
...
}
}
自定义编辑
@RequestMapping("/myInitBinder0954")
@Controller
public class MyInitBinderController {
/*
注册将字符串转换为Date的属性编辑器,该编辑器仅仅对当前controller有效
*/
@InitBinder
public void initBinderXXX(WebDataBinder binder) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
CustomDateEditor dateEditor = new CustomDateEditor(df, true);
binder.registerCustomEditor(Date.class, dateEditor);
}
// http://localhost:8080/myInitBinder0954/test?date=2020-09-03%2010:17:17会使用在
// dongshi.controller.initbinder.MyInitBinderController.initBinderXXX注册的属性编辑器转换为,
// Date类型的
@RequestMapping(value = "/test", method = RequestMethod.GET)
@ResponseBody
public String testFormatData(Date date) {
Map<String, Object> map = new HashMap<>();
map.put("date", date);
return map.toString();
}
}
————————————————
详细用法看原文链接
原文链接:https://blog.csdn.net/wang0907/article/details/108357696