您的位置:首页 > 编程语言 > Java开发

Spring MVC(学习笔记六)控制器的注解(五) -之全局初始化绑定操作(@InitBinder)

2018-02-03 09:15 405 查看

全局初始化绑定操作                                                                         

@InitBinder  定义初始化的方法:不能有返回值,它必须盛名为void。

WebDataBinder:是用来绑定请求参数到指定的属性编辑器.由于前台传到controller里的值是String类型的,当往Model里Set这个值的时候,如果set的这个属性是个对象,Spring就会去找到对应的editor进行转换,然后再SET进去。

首先在HandlerMethodArgumentController(访问路径:/hmac)类编写一个处理方法:

@PostMapping(value = "sib")
public String setInitBinder(Date time){
System.out.println(time);//输出的结果:Fri Nov 11 00:00:00 CST 2011
return "index";
}

再定义一个全局处理的类:GlobalControllerAdiviceController:
@ControllerAdvice
public class GlobalControllerAdiviceController {
//初始化绑定操作【全局形式】
@InitBinder
public void dataBind(WebDataBinder binder){
//设置的格式
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
///給指定类型注册类型转换器操作
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
}

最后在编写index.jsp页面:
<h1>binder</h1>
<form action="${pageContext.request.contextPath}/hmac/sib" method="post">
<input type="text" name="time" value="2011-11-11">
<input type="submit" value="sub">
</form>

自定义转换配置                                                                                                                               

 1. 定义转换类 (继承:PropertyEditorSupport)
  setAsText :设置文本操作
  setValue: 设置值

//包名:editor
public class UserPropertyEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (!StringUtils.isEmpty(text)){

//获取内容,并进行转换操作
String[] userText=text.split(":");
User user=new User();
user.setId(Integer.parseInt(userText[0]));
user.setName(userText[1]);
user.setPwd(userText[2]);

//设置值
setValue(user);
}else{
//...
}
}
}

 2. 注册转换操作:全局处理类:GlobalControllerAdiviceController

@ControllerAdvice
public class GlobalControllerAdiviceController {
/**
* 初始化绑定操作【全局形式】
* @ControllerAdvice(对controller请求进行处理操作(@ReuqestMapping))+@InitBinder(自定义绑定操作)+WebDataBinder(web数据绑定对象)
*/
@InitBinder
public void dataBind(WebDataBinder binder){
//注册自定义转换类型
binder.registerCustomEditor(User.class,new UserPropertyEditor());
}
}


编写index.jsp页面:
<h1>customer binder</h1>
<form action="${pageContext.request.contextPath}/hmac/scb" method="post">
<input type="text" name="us" value="1001:mj:test">
<input type="submit" value="sub">
</form>


我debug调试的结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息