1. package com.chentianyu.controller;
    2. import org.springframework.beans.propertyeditors.CustomDateEditor;
    3. import org.springframework.format.annotation.DateTimeFormat;
    4. import org.springframework.stereotype.Controller;
    5. import org.springframework.web.bind.WebDataBinder;
    6. import org.springframework.web.bind.annotation.InitBinder;
    7. import org.springframework.web.bind.annotation.RequestMapping;
    8. import java.text.SimpleDateFormat;
    9. import java.util.Date;
    10. @Controller
    11. public class MyDateAction {
    12. SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
    13. //单个日期注入
    14. /**
    15. * 日期:<input type="date" name="myDate" /><br>
    16. * @return
    17. */
    18. /*@RequestMapping("/myDate")
    19. public String myDate(@DateTimeFormat(pattern = "yyyy-MM-dd"*//*将字符串转为日期注入进去*//*) Date myDate){
    20. System.out.println(myDate);
    21. System.out.println(sf.format(myDate));
    22. return "show";
    23. }*/
    24. //全局日期处理
    25. //注册一个全局的日期处理注解
    26. @InitBinder
    27. public void initBinder(WebDataBinder dataBinder/*重点*/){
    28. dataBinder.registerCustomEditor(/*转化的类型*/Date.class,/*使用什么工具去转*/new CustomDateEditor(sf,true));
    29. }
    30. @RequestMapping("/myDate")
    31. public String myDate(Date myDate){
    32. System.out.println(myDate);
    33. System.out.println(sf.format(myDate));
    34. return "show";
    35. }
    36. }

    好处是连<mvc:annotation-driven />都省去可以不写