Spring MVC - Binding a Date Field

前端 未结 2 1941
傲寒
傲寒 2020-11-30 20:32

For request parameters representing string, number, and boolean values, the Spring MVC container can bind them to typed properties out of the box.

How do you have th

2条回答
  •  忘掉有多难
    2020-11-30 21:33

    In complement to Arthur's very complete answer : in the case of a simple Date field, you don't have to implement the whole PropertyEditor. You can just use a CustomDateEditor to which you simply pass the date format to use :

    //put this in your Controller 
    //(if you have a superclass for your controllers 
    //and want to use the same date format throughout the app, put it there)
    @InitBinder
    private void dateBinder(WebDataBinder binder) {
                //The date format to parse or output your dates
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
                //Create a new CustomDateEditor
        CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
                //Register it as custom editor for the Date type
        binder.registerCustomEditor(Date.class, editor);
    }
    

提交回复
热议问题