如何在对Spring MVC Controller的GET请求中接受Date params?

Lit*_*ski 113 java spring date spring-mvc

我有一个GET请求,它将YYYY-MM-DD格式的日期发送给Spring Controller.控制器代码如下:

@RequestMapping(value="/fetch" , method=RequestMethod.GET)
    public @ResponseBody String fetchResult(@RequestParam("from") Date fromDate) {
        //Content goes here
    }
Run Code Online (Sandbox Code Playgroud)

正在我使用Firebug进行检查时,请求已正确发送.我收到错误:

HTTP状态400:客户端发送的请求在语法上不正确.

如何让控制器接受这种格式的日期?请帮忙.我究竟做错了什么?

Lit*_*ski 232

好的,我解决了.写给那些在一整天的不间断编码后可能会感到疲倦并且错过这么愚蠢的事情的人.

@RequestMapping(value="/fetch" , method=RequestMethod.GET)
    public @ResponseBody String fetchResult(@RequestParam("from") @DateTimeFormat(pattern="yyyy-MM-dd") Date fromDate) {
        //Content goes here
    }
Run Code Online (Sandbox Code Playgroud)

是的,这很简单.只需添加DateTimeFormat注释即可.

  • 我打算写一个答案,但你打败了我.您也可以使用@DateTimeFormat(iso = ISO.DATE),它的格式相同.顺便说一句,如果你能建议你使用Joda DateTime库.Spring非常支持它. (16认同)
  • @Luciano当然你也可以做@DateTimeFormat(iso = ISO.DATE_TIME) (2认同)
  • @thorinkor在Spring Boot中,您可以在application.properties中设置spring.mvc.date-format属性,或者添加实现org.springframework.format接口的bean(扩展org.springframework.format.datetime。 DateFormatter`可能是解决方法)。在非启动Spring中,您可以@Override WebMvcConfigurerAdapter的addFormatters方法,并在其中添加实现Formatter的bean。 (2认同)

小智 8

下面的解决方案非常适合 Spring Boot 应用程序。

控制器:

@GetMapping("user/getAllInactiveUsers")
List<User> getAllInactiveUsers(@RequestParam("date") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date dateTime) {
    return userRepository.getAllInactiveUsers(dateTime);
}
Run Code Online (Sandbox Code Playgroud)

因此,在调用者中(在我的例子中是网络流量),我们需要以这种(“yyyy-MM-dd HH:mm:ss”)格式传递日期时间。

呼叫方:

public Flux<UserDto> getAllInactiveUsers(String dateTime) {
    Flux<UserDto> userDto = RegistryDBService.getDbWebClient(dbServiceUrl).get()
            .uri("/user/getAllInactiveUsers?date={dateTime}", dateTime).retrieve()
            .bodyToFlux(User.class).map(UserDto::of);
    return userDto;
}
Run Code Online (Sandbox Code Playgroud)

存储库:

@Query("SELECT u from User u  where u.validLoginDate < ?1 AND u.invalidLoginDate < ?1 and u.status!='LOCKED'")
List<User> getAllInactiveUsers(Date dateTime);
Run Code Online (Sandbox Code Playgroud)

干杯!!


小智 5

这是我从前端获取格式化日期的操作

  @RequestMapping(value = "/{dateString}", method = RequestMethod.GET)
  @ResponseBody
  public HttpStatus getSomething(@PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String dateString) {
   return OK;
  }
Run Code Online (Sandbox Code Playgroud)

您可以使用它来获取所需的内容。

  • 没明白。如果您将dateString作为字符串而不是Date接收,则将@ DateTimeFormat添加到@ PathVariable有什么意义? (9认同)

小智 5

...或者您可以以正确的方式进行操作,并为整个应用程序中的日期序列化/反序列化制定一致的规则。把它放在application.properties中:

spring.mvc.date-format=yyyy-MM-dd
Run Code Online (Sandbox Code Playgroud)