springmvc框架后台Date类型字段接收数据

 

 

 

在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

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜空繁星vv

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值