@InitBinder

本文详细介绍了Spring MVC中@InitBinder注解的作用及其用法,包括如何使用它来定制参数绑定过程,以及如何实现全局配置。此外还探讨了通过@ControllerAdvice进行全局配置的方法,并简要介绍了@ExceptionHandler和@ModelAttribute的应用。

转载自:
  https://blog.youkuaiyun.com/ai_xiangjuan/article/details/79842385
  https://blog.youkuaiyun.com/ai_xiangjuan/article/details/79696639

@InitBinder用于在@Controller中标注于方法上,表示为当前控制器注册一个属性编辑器,只对当前的Controller有效。@InitBinder标注的方法必须有一个参数WebDataBinder。所谓的属性编辑器可以理解就是帮助我们完成参数绑定。

    @ResponseBody
    @RequestMapping(value = "/test")
    public String test(@RequestParam String name,@RequestParam Date date) throws Exception {
        System.out.println(name);
        System.out.println(date);
        return name;
    }

    @InitBinder
    public void initBinder(WebDataBinder binder){
        binder.registerCustomEditor(String.class,
                new StringTrimmerEditor(true));

        binder.registerCustomEditor(Date.class,
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));

    }

上面例子中,@InitBinder方法会帮助我们把String类型的参数先trim再绑定,而对于Date类型的参数会先格式化在绑定。例如当请求是/test?name=%20zero%20&date=2018-05-22时,会把zero绑定到name,再把时间串格式化为Date类型,再绑定到date。

这里的@InitBinder方法只对当前Controller生效,要想全局生效,可以使用@ControllerAdvice。通过@ControllerAdvice可以将对于控制器的全局配置放置在同一个位置,注解了@ControllerAdvice的类的方法可以使用@ExceptionHandler@InitBinder@ModelAttribute注解到方法上,这对所有注解了@RequestMapping的控制器内的方法有效。

@ControllerAdvice
public class GlobalControllerAdvice {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class,
                new StringTrimmerEditor(true));

        binder.registerCustomEditor(Date.class,
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));

    }
}

除了使用@ControllerAdvice来配置全局的WebDataBinder,还可以使用RequestMappingHandlerAdapter

    @Bean
    public RequestMappingHandlerAdapter webBindingInitializer() {
        RequestMappingHandlerAdapter adapter = new RequestMappingHandlerAdapter();
        adapter.setWebBindingInitializer(new WebBindingInitializer(){

            @Override
            public void initBinder(WebDataBinder binder, WebRequest request) {
                binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));

            }
        });
        return adapter;
    }

如上示例,可以实现同样的效果。


@ControllerAdvice中除了配置@InitBinder,还可以有@ExceptionHandler用于全局处理控制器里面的异常;@ModelAttribute作用是绑定键值对到Model里,让全局的@RequestMapping都能获得在此处设置的键值对。

补充:如果 @ExceptionHandler注解中未声明要处理的异常类型,则默认为方法参数列表中的异常类型。示例:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    String handleException(Exception e){
        return "Exception Deal! " + e.getMessage();
    }
}
### @InitBinder 注解的作用 `@InitBinder` 是 Spring MVC 提供的一个注解,用于在请求处理之前初始化 `WebDataBinder` 对象。通过该注解标记的方法可以自定义数据绑定逻辑,例如注册属性编辑器(PropertyEditor),以支持特定类型的转换或格式化操作。这在处理复杂类型如日期、枚举等时非常有用,因为默认的数据绑定机制可能无法直接处理这些类型 [^4]。 ### 使用场景 在实际开发中,当需要将 HTTP 请求参数自动绑定到控制器方法的参数上时,默认情况下,Spring MVC 会使用内置的 `DataBinder` 来完成这一任务。然而,在某些情况下,开发者可能希望对绑定过程进行定制,比如: - 将字符串转换为 `Date` 类型。 - 忽略某些字段,防止其被绑定。 - 自定义验证规则。 - 添加自定义的 `PropertyEditor` 或 `Converter`。 在这种情况下,`@InitBinder` 提供了灵活的方式来实现上述需求。 ### 示例代码 以下是一个典型的 `@InitBinder` 使用示例,展示如何将请求参数中的日期字符串转换为 `Date` 类型: ```java import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.stereotype.Controller; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import java.text.SimpleDateFormat; import java.util.Date; @Controller public class MyController { @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); } @PostMapping("/submit") public String submitForm(@RequestParam("date") Date date) { // 使用绑定后的日期对象处理逻辑 System.out.println("Received date: " + date); return "result"; } } ``` 在这个例子中,`initBinder` 方法通过 `@InitBinder` 注解被标记为数据绑定器的初始化方法。它创建了一个 `SimpleDateFormat` 实例来解析日期字符串,并将其注册为 `Date` 类型的自定义编辑器。这样,当控制器接收到包含日期参数的 POST 请求时,Spring MVC 会自动使用这个编辑器将字符串转换为 `Date` 对象 [^2]。 ### 局限性与注意事项 虽然 `@InitBinder` 提供了强大的功能,但在使用时也需要注意一些限制和最佳实践: - **作用范围**:`@InitBinder` 标记的方法只会影响同一个控制器类中的请求处理方法。如果希望全局生效,可以考虑继承 `WebMvcConfigurer` 并重写 `addFormatters` 方法。 - **线程安全**:由于 `WebDataBinder` 是每个请求单独创建的,因此不需要担心线程安全问题。 - **避免重复绑定**:确保不要多次注册相同的 `PropertyEditor`,以免造成不必要的性能开销。 - **兼容性**:对于较新的 Spring 版本,推荐使用 `Converter` 和 `Formatter` 接口替代传统的 `PropertyEditor`,因为它们提供了更好的灵活性和可复用性。 ### 总结 `@InitBinder` 是一个非常有用的工具,尤其适用于需要对数据绑定过程进行细粒度控制的场景。通过合理使用 `@InitBinder`,开发者可以轻松实现复杂的类型转换和格式化逻辑,从而提升应用程序的功能性和健壮性。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值