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; }
上一篇:浅谈WebService的版本兼容性设计


下一篇:你真的会使用SQL Server的备份还原功能吗?之一:恢复模型