简体   繁体   English

为Spring 4 @RequestParam或@PathVariable注册自定义转换器的正确方法是什么

[英]What is the correct way to register a custom converter for Spring 4 @RequestParam or @PathVariable

I am trying to figure out what is the "best" or recommended way for customer converters for RequestParams and PathVariables in Spring 4? 我试图弄清楚在Spring 4中客户转换器对RequestParams和PathVariables的“最佳”或推荐方式是什么? We have registered our Jackson JSON converters, but they don't work for these parameters, and from reading online I've found about a dozen different answers on what should be done. 我们已经注册了Jackson JSON转换器,但是它们不适用于这些参数,通过在线阅读,我发现了关于应该做什么的大约十二种不同答案。

I originally thought LocalDateTime would work without a custom converter with the standard ISO format yyyy-MM-ddThh:mm:ss but when I pass that up (2014-12-01T01:01:01) it just throws an exception, and I tried different formats to see if those would work, but so far none of the formats I've tried have worked, so I was going to try a custom converter, but I can't seem to find what the correct way to do that is either. 我原本以为LocalDateTime可以在没有标准ISO格式yyyy-MM-ddThh:mm:ss的自定义转换器的情况下工作,但是当我将其传递给(2014-12-01T01:01:01)时,它只是引发了异常,因此我尝试了不同的格式以查看它们是否可行,但是到目前为止,我尝试过的所有格式都没有奏效,所以我打算尝试使用自定义转换器,但是我似乎找不到正确的方法。

@RequestMapping(value = "/foo")
@RestController
public class TestController{
    @RequestMapping(value="/test", method=RequestMethod.GET)
    public void test(@RequestParam("stuff") LocalDateTime source) {
        int i = 0;
    }
}

Here is the sample url I tried http://localhost:8081/data/foo/test?start=1986-04-08T12:30:00 这是我尝试的示例URL http://localhost:8081/data/foo/test?start=1986-04-08T12:30:00

The proper formatting for your case would be 适合您的情况的格式为

@RequestMapping(value="/test", method= RequestMethod.GET)
public void test(@RequestParam("stuff")  @DateTimeFormat(iso=ISO.DATE_TIME) LocalDateTime source) {
    int i = 0;
}

just make sure one thing, in the value you pass and state in your question 2014-12-01T:01:01:01 you have a typo, it should be 2014-12-01T01:01:01 so no semi-colon betweeen T and 01 只需确保一件事,在您传递的值中并在问题中2014-12-01T:01:01:01您有错字,应该是2014-12-01T01:01:01所以不要使用分号T01

try checking out the @DateTimeFormat Parameter Annotation which was introduced with Spring 3 Type Conversions and Validations : 尝试查看由Spring 3类型转换和验证引入的@DateTimeFormat参数注释:

@RequestMapping(value = "/appointments/{day}", method = RequestMethod.GET)
public String getAppointmentsForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day) {
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM