W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
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
mvcValidator
method fromWebMvcConfigurationSupport
and declare the method to explicitly returnLocalValidatorFactory
rather thanValidator
. 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視圖中被渲染。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: