Spring之InitBinder的功能简介说明
下文笔者讲述Spring中InitBinder注解的功能简介说明,如下所示
InitBinder注解的功能
@InitBinder注解: 1.用于初始化绑定器Binder Binder用于绑定数据 2.将请求参数转成数据对象 从上面的表述上,我们可以得出InitBinder注解的功能: 类型转换和参数绑定
@InitBinder使用场景说明
@InitBinder注解放在@Controller方法上: 为当前控制器注册一个属性编辑器或其他
@InitBinder注解的示例
类型转换
将“2023-11-08 22:16:18” 字符串转为java.util.Date对象 @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); }
参数绑定
<form action="/test" method="post"> name: <input type="text" name="customer.name"> <br> age: <input type="text" name="customer.customerId"> <br> name: <input type="text" name="goods.title"> <br> age: <input type="text" name="goods.price"> <br> <input type="submit"> </form> //将以customer为前缀的参数绑定到Customer对象上 //将以goods为前缀的参数绑定到Goods对象上 @InitBinder("customer") public void initCustomer(WebDataBinder binder) { binder.setFieldDefaultPrefix("customer."); } @InitBinder("goods") public void initGoods(WebDataBinder binder) { binder.setFieldDefaultPrefix("goods."); } @PostMapping("/test") public ModelAndView test(Customer customer, @ModelAttribute("goods") Goods goods, ModelAndView mv) { // do something return mv; } //@ModelAttribute("goods") 中“goods” //用于设置@InitBinder("goods") //在initGoods方法中 //使用goods为前缀的参数封装为名为goods 的对象; //在test方法中 //使用@ModelAttribute("goods") 来接收名等于goods对象
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。