Spring MVC 驗(yàn)證支持

2018-07-26 14:51 更新

Spring提供了一個(gè)驗(yàn)證器Validator接口,應(yīng)用的任何一層都可以使用它來做驗(yàn)證。在Spring MVC中,你可以配置一個(gè)全局的Validator實(shí)例,用以處理所有注解了@Valid的元素或注解了@Validated的控制器方法參數(shù)、以及/或在控制器內(nèi)的@InitBinder方法中用作局部的Validator。全局驗(yàn)證器與局部驗(yàn)證器實(shí)例可以結(jié)合起來使用,提供組合驗(yàn)證。

Spring還支持JSR-303/JSR-349的Bean驗(yàn)證。這是通過LocalValidatorFactoryBean類實(shí)現(xiàn)的,它為Spring的驗(yàn)證器接口org.springframework.validation.Validator到Bean驗(yàn)證的javax.validation.Validator接口做了適配。這個(gè)類可以插入到Spring MVC的上下文中,作為一個(gè)全局的驗(yàn)證器,如下所述。

如果在classpath下存在Bean驗(yàn)證器,諸如Hibernate Validator等,那么@EnableWebMvc<mvc:annotation-driven>默認(rèn)會(huì)自動(dòng)使用LocalValidatorFactoryBean為Spring MVC應(yīng)用提供Bean驗(yàn)證的支持。

有時(shí),能將LocalValidatorFactoryBean直接注入到控制器或另外一個(gè)類中會(huì)更方便。

Sometimes it's convenient to have a LocalValidatorFactoryBean injected into a controller or another class. The easiest way to do that is to declare your own @Bean and also mark it with @Primary in order to avoid a conflict with the one provided with the MVC Java config.

If you prefer to use the one from the MVC Java config, you'll need to override the mvcValidatormethod from WebMvcConfigurationSupport and declare the method to explicitly return LocalValidatorFactory rather than Validator. See Section 21.16.13, "Advanced Customizations with MVC Java Config" for information on how to switch to extend the provided configuration.

此外,你也可以配置你自己的全局Validator驗(yàn)證器實(shí)例:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public Validator getValidator(); {
        // return "global" validator
    }

}

XML中做法如下:

<?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>

若要同時(shí)使用全局驗(yàn)證和局部驗(yàn)證,只需添加一個(gè)(或多個(gè))局部驗(yàn)證器即可:

@Controller
public class MyController {

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.addValidators(new FooValidator());
    }

}

做完這個(gè)最少的配置之后,任何時(shí)候只要方法中有參數(shù)注解了@Valid@Validated,配置的驗(yàn)證器就會(huì)自動(dòng)對(duì)它們做驗(yàn)證。任何無法通過的驗(yàn)證都會(huì)被自動(dòng)報(bào)告為錯(cuò)誤并添加到BindingResult對(duì)象中去,你可以在方法參數(shù)中聲明它并獲取這些錯(cuò)誤,同時(shí)這些錯(cuò)誤也能在Spring MVC的HTML視圖中被渲染。


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)