如何在对 Spring MVC 控制器的 GET 请求中接受日期参数? [英] How to accept Date params in a GET request to Spring MVC Controller?
问题描述
我有一个 GET 请求,它将 YYYY-MM-DD 格式的日期发送到 Spring 控制器.控制器代码如下:
I've a GET request that sends a date in YYYY-MM-DD format to a Spring Controller. The controller code is as follows:
@RequestMapping(value="/fetch" , method=RequestMethod.GET)
public @ResponseBody String fetchResult(@RequestParam("from") Date fromDate) {
//Content goes here
}
请求已正确发送,因为我正在使用 Firebug 进行检查.我收到错误:
The request is sent correctly as I'm checking with Firebug. I get the error:
HTTP 状态 400:客户端发送的请求在语法上不正确.
HTTP Status 400: The request sent by the client was syntactically incorrect.
如何让控制器接受这种格式的日期?请帮忙.我做错了什么?
How can I make the controller accept this format of Date? Please help. What am I doing wrong?
推荐答案
好的,我解决了.为那些在一整天不间断编码后可能会感到疲倦的人编写它错过这么傻的事情.
Ok, I solved it. Writing it for anyone who might be tired after a full day of non-stop coding & miss such a silly thing.
@RequestMapping(value="/fetch" , method=RequestMethod.GET)
public @ResponseBody String fetchResult(@RequestParam("from") @DateTimeFormat(pattern="yyyy-MM-dd") Date fromDate) {
//Content goes here
}
是的,很简单.只需添加 DateTimeFormat 注释即可.
Yes, it's simple. Just add the DateTimeFormat annotation.
这篇关于如何在对 Spring MVC 控制器的 GET 请求中接受日期参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!