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

springMVC @initBinder 使用

2015-11-10 13:15 465 查看
controller代码:

@Controller
public class WelcomeController {

@InitBinder
public void iniiBinder(WebDataBinder binder){

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

@RequestMapping("/welcome")
public void welcome(HttpServletResponse response ,Date date) throws IOException{

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

response.getWriter().write("welcome here again !  current date is "+format.format(date));
}

}


url : http://localhost:8080/mymvc/welcome?date=2015-11-10

浏览器输出:welcome here again ! current date is 2015-11-10

备注:

initBinder 注解方法首先执行,然后执行requestMapping注解方法,字符串参数自动转成了指定的日期。如果是spring 的版本大于等于4.2 则 @initBinder 方法也可以写作

@InitBinder
public void initBinder(WebDataBinder binder) {
binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
}

有一个问题是initBinder 只对当前controller起左右,其它controller无效,如何让initBinder 对所有controller有效呢?我还没有研究出来哈。

-------------------- 华丽的分割线 -------------------------------------------------------

关于@initBinder 对所有 controller 都有效有了解决方案。

利用 @ControllerAdvice注解 。在有此注解的类里 写 @initBinder 方法,并指明目标 类,则可对目标类起作用。

有三种 方式制定目标类:

// Target all Controllers annotated with @RestController
@ControllerAdvice(annotations = RestController.class)
public class AnnotationAdvice {}

// Target all Controllers within specific packages
@ControllerAdvice("org.example.controllers")
public class BasePackageAdvice {}

// Target all Controllers assignable to specific classes
@ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class})
public class AssignableTypesAdvice {}


我选的第二种,目标锁定到指定的包下所有的类。
代码如下

@ControllerAdvice("com.lls.mvc")
public class BasePackageAdvice {

@InitBinder
public void iniiBinder(WebDataBinder binder){

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
format.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(format, false));
}
注意 在配置文件中将该类扫描

<context:component-scan
base-package="com.lls.config"
/>
这样 就可以将其它的controller的关于日期的initBinder注解方法去掉了。
每次请求都会先调用 @ControllerAdvice 类下的 @initBinder 方法。然后再调用 controller的 @requestMapping 对应的方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring mvc initBinder