What is the purpose of init binder in spring MVC

2019-01-10 08:42发布

问题:

This is the code on internet for init binder

@InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

Can anyone please explain:

1) Why is it used, I mean, what was the problem before , how it was solved with that function. so i want to know what was the problem with orginal date which was solved with this date format?

2) How to use this format from the JSP form point of view, I mean, if we enter date in text format , does it covert to specific format and then save it?

3) How does it apply that formatting , I mean , do we have to do something in object class ?

回答1:

1) Before, you had to resort to manually parsing the date:

 public void webmethod(@RequestParam("date") String strDate) {
    Date date = ... // manually parse the date
 }

Now you can get the parsed date directly:

 public void webmethod(@RequestParam("date") Date date) {
 }

2) If your jsp page supplies a date on the form yyyy-MM-dd you can retrieve it as a Date object directly in your controller.

3) Spring tries against all registered editors to see if values can be converted into objects. You don't have to do anything in the object itself, that's the beauty of it.