[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
}

 

posted @ 2021-01-13 00:39  Zhentiw  阅读(82)  评论(0编辑  收藏  举报