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;
    
    }
  • 相关阅读:
    Lc20-Valid Parentheses
    Lc262-行程和用户
    Lc197-Rising Temperature
    Lc196-删除重复的电子邮箱
    Lc185-部门工资前三高的所有员工
    Lc18-四数之和
    Lc17-电话号码的字母组合
    Netty Java NIO 基本介绍 之 Selector,ServerSocketChannel , SocketChannel (二)
    Netty(二)工作原理模型
    Netty 异步模型
  • 原文地址:https://www.cnblogs.com/beiyeren/p/3370357.html
Copyright © 2011-2022 走看看