springboot 使用RequestBody接收日期类型可以正常转换为什么url传参就转换失败了?怎么解决?
在Spring Boot中,当使用@RequestBody接收日期类型时,Spring会自动使用Jackson将日期字符串转换为日期对象。但是,当使用URL传参时,Spring会将参数作为字符串处理,而不会自动进行日期转换。
为了解决这个问题,可以使用Spring Boot提供的@InitBinder注解,来自定义日期转换器。通过在控制器中定义一个日期转换器,将日期字符串转换为日期对象,即可实现URL传参的日期转换。
具体代码如下:
@Controller
public class MyController {
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
@RequestMapping("/test")
public String test(Date date) {
System.out.println(date);
return "test";
}
}
在上述代码中,我们通过@InitBinder注解定义了一个日期转换器,并将其注册到WebDataBinder中。在控制器中使用Date类型的参数来接收日期参数,Spring会自动使用我们定义的转换器将日期字符串转换为Date对象。
这样,就可以实现URL传参的日期转换了
原文地址: https://www.cveoy.top/t/topic/huyK 著作权归作者所有。请勿转载和采集!