The role of SpringMVC's @InitBinder

I. Introduction

In SpringMVC, the @InitBinder annotation is used to customize data binding methods. When submitting data using a form, SpringMVC will bind the request parameters into Java objects. However, sometimes the data format of the request parameters may be inconsistent with the attribute format of the Java object. In this case, you need to use the @InitBinder annotation to customize the data binding method.

The method annotated with @InitBinder will be called before each request is processed, and can be used to process the request parameters and convert them into the format of Java object attributes. The @InitBinder annotated method must return void type and must accept a WebDataBinder parameter.

2. Examples

@Controller  
public class UserController {  
  
    @InitBinder  
    public void initBinder(WebDataBinder binder) {  
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
        dateFormat.setLenient(false);  
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));  
    }  
  
    @RequestMapping("/user")  
    public String addUser(User user) {  
        // 处理用户信息  
        return "success";  
    }  
}

In the above example, we defined an initBinder method using the @InitBinder annotation. In this method, we create a date format object using the SimpleDateFormat class and set it to non-relaxed mode. Then, we call the registerCustomEditor method of WebDataBinder to register a custom date editor. This custom date editor will convert the date string in the request parameter to the Date type in the Java object.

In the addUser method that handles user information, we can directly use the User object to receive request parameters without worrying about the format conversion of date strings. Because the initBinder method annotated with @InitBinder has converted the request parameters into the format of Java object properties before each request is processed.

It should be noted that the method annotated with @InitBinder will be called before each request is processed, so time-consuming operations should not be performed in this method. At the same time, if there are multiple methods for processing requests in a Controller, each method will execute the @InitBinder annotated method once. Therefore, if there are multiple methods that need to use the same data binding rules, the @InitBinder annotated method can be extracted into a common parent class or configuration file.

Guess you like

Origin blog.csdn.net/weixin_52721608/article/details/133530926