[Java Spring] @InitBinder

For example, from the client, it send date as string to BE. But BE requires date to be a Date instead of String. 

Controller:

..

@Autowired
private UserRepository userRepository;

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(
        // convert to 
        Date.class,
        // prop which need to be converted
        "dateOfBirth",
        new CustomDateEditor(new SimpleDateFormat("yyy-MM-dd")),
        true);
}

@PostMapping("/registeruser")
public String registerUser(@Valid @ModelAttribute("newuser") User user, BindingResult result, Model model) {
    ....
    System.out.print(user.getDateOfBirth()) // should be the date object
}
原文地址:https://www.cnblogs.com/Answer1215/p/14270106.html