spring mvc中的valid

时间:2023-03-08 16:49:40

当你希望在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; }