zoukankan      html  css  js  c++  java
  • spring mvc中的valid

    当你希望在spring mvc中直接校验表单参数时,你可以采用如下操作:

    声明Validator的方式:

    1.为每一个Controller声明一个Validator

    @Controller
    public class MyController {
    
       @InitBinder
       protected void initBinder(WebDataBinder binder) {
          binder.setValidator(new FooValidator());
        }
    }
    2.为所有的Controller声明一个Validator
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
         xmlns:mvc="http://www.springframework.org/schema/mvc"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        
        <mvc:annotation-driven validator="globalValidator"/>
    </beans>
    如果你希望在spring mvc中使用jsr303实现类校验,则需要把jsr303实现类,比如hibernate Validator,放到classpath中,spring会自动扫描进行校验.
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
         xmlns:mvc="http://www.springframework.org/schema/mvc"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        
        <mvc:annotation-driven />
    </beans>

    如果你希望在实体类中主动使用这个校验类,如下操作:

    <bean id="validator"
      class="org.springframework.validation.beanvalidation.LocalValidator FactoryBean"/>

    使用spring 依赖注入即可.

    import javax.validation.Validator;
    
    @Service
    public class MyService {
      
      @Autowired
      private Validator validator;
    
    }
  • 相关阅读:
    OpenJTAG与Jlink/Jlink的区别
    Ubunut 10.04 upgrade git
    HEVC播放器出炉,迅雷看看支持H.265
    平铺文理+拉伸按钮图片
    黑马程序员java基础学习IO流4
    Excel 2010实战技巧精粹
    昆明虚假楼盘吸引 2 千多人购买诈骗近 3 亿
    Canonical 公司预计最晚明年 4 月推出 Ubuntu 中国版
    Canonical 公司预计最晚明年 4 月推出 Ubuntu 中国版
    十二个理由让你不得不期待 Ubuntu10.10
  • 原文地址:https://www.cnblogs.com/beiyeren/p/3370357.html
Copyright © 2011-2022 走看看