Spring MVC 映射Date类型参数的解决方案

https://blog.csdn.net/qq_16313365/article/details/54408474

 在Spring MVC中,无法直接将Date类型的数据映射绑定到Controller方法的参数中,因为Spring本身不支持这种类型的转换,所以这里有两种解决方案供小伙伴儿们参考一下下。


1.自定义格式转换(荐)

        在Controller中使用InitBinder(该注解在Spring2.5之后才有)注解来定义如下方法,即可解决Date类型转换问题:

[java]  view plain  copy
  1. /** 
  2.      * 自定义方法绑定请求参数的Date类型 
  3.      *  
  4.      * @param request 
  5.      * @param binder 
  6.      * @throws Exception 
  7.      */  
  8.     @InitBinder  
  9.     protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {  
  10.         DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  11.         CustomDateEditor editor = new CustomDateEditor(df, true);//true表示允许为空,false反之  
  12.         binder.registerCustomEditor(Date.class, editor);  
  13.     }  

2.单独映射该参数(土)

        当然了,最土的方法莫过于把这个Date类型的参数单独映射为String类型,然后自己再通过程序将其转换为Date类型:

[java]  view plain  copy
  1. @RequestMapping(value = "test")  
  2. public String test(ModelMap model, String date) throws ParseException {  
  3.     Date d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);  
  4.     // ...接下来怎么做咯  
  5.     return "test";  
  6. }  


猜你喜欢

转载自blog.csdn.net/nrlovestudy/article/details/80284922