校验器

@InitBinder

interface Validator

springMVC @initBinder 使用


controller代码:
  1.  
    @Controller
  2.  
    public class WelcomeController {
  3.  
     
  4.  
    @InitBinder
  5.  
    public void iniiBinder(WebDataBinder binder){
  6.  
     
  7.  
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  8.  
    format.setLenient( false);
  9.  
    binder.registerCustomEditor(Date.class, new CustomDateEditor(format, false));
  10.  
    }
  11.  
     
  12.  
     
  13.  
    @RequestMapping("/welcome")
  14.  
    public void welcome(HttpServletResponse response ,Date date) throws IOException{
  15.  
     
  16.  
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  17.  
     
  18.  
    response.getWriter().write( "welcome here again ! current date is "+format.format(date));
  19.  
    }
  20.  
     
  21.  
    }


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 方法也可以写作

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

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

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

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

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

有三种 方式制定目标类:

  1.  
    // Target all Controllers annotated with @RestController
  2.  
    @ControllerAdvice(annotations = RestController.class)
  3.  
    public class AnnotationAdvice {}
  4.  
     
  5.  
    // Target all Controllers within specific packages
  6.  
    @ControllerAdvice("org.example.controllers")
  7.  
    public class BasePackageAdvice {}
  8.  
     
  9.  
    // Target all Controllers assignable to specific classes
  10.  
    @ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class})
  11.  
    public class AssignableTypesAdvice {}
我选的第二种,目标锁定到指定的包下所有的类。

代码如下

  1.  
    @ControllerAdvice("com.lls.mvc")
  2.  
    public class BasePackageAdvice {
  3.  
     
  4.  
    @InitBinder
  5.  
    public void iniiBinder(WebDataBinder binder){
  6.  
     
  7.  
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  8.  
    format.setLenient( false);
  9.  
    binder.registerCustomEditor(Date.class, new CustomDateEditor(format, false));
  10.  
    }
注意 在配置文件中将该类扫描

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

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

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

猜你喜欢

转载自www.cnblogs.com/longxok/p/10925255.html
今日推荐