@InitBinder 注解

@InitBinder 注解

介绍

@InitBinder注解可以作用在被@Controller注解的类的方法上,表示为当前控制器注册一个属性编辑器,用于对WebDataBinder进行初始化,且只对当前的Controller有效。@InitBinder标注的方法会被多次执行的,也就是说来一次请求就会执行一次@InitBinder注解方法的内容。

  1. @InitBinder注解是在其所标注的方法执行之前被解析和执行;
  2. @InitBinder的value属性,控制的是模型Model里的KEY,而不是方法名;
  3. @InitBinder标注的方法也不能有返回值;
  4. @InitBinder对@RequestBody这种基于消息转换器的请求参数是失效的。

@InitBinder 是 Spring MVC 中的一个注解,用于初始化数据绑定器。它通常用来为特定的请求设置自定义的编辑器,以便将请求参数转换为特定的目标对象类型。通过这种方式,可以控制如何从请求参数中解析数据并将其绑定到 Java 对象中。

作用

用于将前端传递过来的数据进行类型转换或者叫属性编辑,如:将前端传递过来的字符串格式的日期数据,转化为DATE类型。

范围

@InitBinder是属于Controller级别的属性编辑器,并非全局级别(针对所有Controller)的属性编辑器,也就是一个@InitBinder只对当前所在的Controller有效,对其他Controller无效的,如果项目中有多个Controller中都要进属性编辑怎么办呢?一般我们将@InitBinder标注的方法定义在基础的控制器上,所有具体的Controller继承这个基础的Controller即可。

示例

以下是一个使用 @InitBinder 注解的示例:

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";
    }
}

在这个示例中:

  1. @InitBinder 注解的方法 initBinder 接收一个 WebDataBinder 对象。
  2. initBinder 方法中,我们创建了一个自定义的日期编辑器 CustomDateEditor,并将其注册到 WebDataBinder。这样,在处理请求参数时,Spring MVC 会使用这个自定义的编辑器将请求中的字符串日期转换为 Date 对象。
  3. submitForm 方法处理 POST 请求,并接收一个 @RequestParam 注解的 Date 对象。由于我们在 initBinder 方法中注册了自定义编辑器,Spring MVC 会自动将请求参数中的日期字符串转换为 Date 对象并传递给 submitForm 方法。

通过 @InitBinder,我们可以轻松地为特定的请求参数设置自定义的转换逻辑,确保数据绑定过程中的灵活性和可扩展性。

[SpringBoot - @InitBinder注解详解-优快云博客](

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值