@InitBinder
interface Validator
springMVC @initBinder 使用
controller代码:
-
-
public class WelcomeController {
-
-
-
public void iniiBinder(WebDataBinder binder){
-
-
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
-
format.setLenient( false);
-
binder.registerCustomEditor(Date.class, new CustomDateEditor(format, false));
-
}
-
-
-
-
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 方法也可以写作
-
-
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
-
-
public class AnnotationAdvice {}
-
-
// Target all Controllers within specific packages
-
-
public class BasePackageAdvice {}
-
-
// Target all Controllers assignable to specific classes
-
-
public class AssignableTypesAdvice {}
代码如下
-
-
public class BasePackageAdvice {
-
-
-
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 对应的方法。