zl程序教程

您现在的位置是:首页 >  后端

当前栏目

[Java Spring] @InitBinder

2023-09-14 08:59:13 时间

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
}