springMVC @initBinder 使用

来源:互联网 发布:crf算法 java 编辑:程序博客网 时间:2024/06/13 01:08

controller代码:

@Controllerpublic class WelcomeController {@InitBinderpublic 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 {@InitBinderpublic void iniiBinder(WebDataBinder binder){SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");format.setLenient(false);binder.registerCustomEditor(Date.class, new CustomDateEditor(format, false));}
注意 在配置文件中将该类扫描

<context:component-scanbase-package="com.lls.config"/>

这样 就可以将其它的controller的关于日期的initBinder注解方法去掉了。

每次请求都会先调用 @ControllerAdvice 类下的 @initBinder 方法。然后再调用 controller的 @requestMapping 对应的方法。



1 0