@Valid springMVC bean校验不起作用
@RequestMapping("/add2")
public String addStudentValid(@Valid @ModelAttribute("s") Student s,BindingResult result){
if(result.hasErrors()){
List<FieldError> fieldErrors = result.getFieldErrors();
for (FieldError fieldError : fieldErrors) {
log.info("errors --"+fieldError.getField()+fieldError.getDefaultMessage());
}
}
log.info("s.name="+s.getName());
log.info("s.age="+s.getAge());
return "success";
}
import javax.validation.constraints.Min;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty; public class Student { @NotEmpty
@Length(min=4,message="{stu.name}")
private String name;
@Min(value=18,message="{stu.age}")
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
} @Override
public String toString() {
return "toString - name="+name+";age="+age;
} }
需要开启注解 <mvc:annotation-driven/>才能启用验证。否则@valid不管用。
如果要使用错误提示的国际化消息,如stu.name为properties文件中的键值对
@Length(min=4,message="{stu.name}")
则需要在dispatcher-servlet.xml中配置
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:validmessages"/>
<property name="fileEncodings" value="utf-8"/>
<property name="cacheSeconds" value="120"/>
</bean> <!-- 以下 validator ConversionService 在使用 mvc:annotation-driven 会 自动注册-->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
<!-- 如果不加默认到 使用classpath下的 ValidationMessages.properties -->
<property name="validationMessageSource" ref="messageSource" />
</bean> <mvc:annotation-driven validator="validator"/>
在src/main/resources下放入validmessages.properties即可。
上面的配置设置了自定义validator,使用messageSource为错误消息提示资源文件。
validmessages.properties内容为
stu.name=\u540D\u79F0\u7684\u957F\u5EA6\u4E0D\u80FD\u5C0F\u4E8E{min}\u554A!
stu.age=\u5E74\u9F84\u5FC5\u987B\u5927\u4E8E{value}\u5C81\u554A!
可以通过{value} {min} {max}等引用注解里的值。
当名称长度小于4 age小于18 输出:
名称的长度不能小于4啊!
age年龄必须大于18岁啊!
本次测试的dispatcher-servlet.xml为
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
"> <context:component-scan base-package="com.upper"/> <!-- freemarker的配置 -->
<bean id="freemarkerConfigurer"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/views/" />
<property name="defaultEncoding" value="GBK" />
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">0</prop>
<prop key="locale">zh_CN</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
<prop key="date_format">yyyy-MM-dd</prop>
<prop key="number_format">#.##</prop>
<!-- <prop key="auto_import">c_index.tpl as p</prop> -->
</props>
</property>
</bean>
<!-- FreeMarker视图解析 如返回userinfo。。在这里配置后缀名ftl和视图解析器。。 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" />
<property name="suffix" value=".ftl" />
<property name="contentType" value="text/html;charset=GBK" />
<property name="exposeRequestAttributes" value="true" />
<property name="exposeSessionAttributes" value="true" />
<property name="exposeSpringMacroHelpers" value="true" />
<property name="requestContextAttribute" value="rc" />
<property name="allowSessionOverride" value="true"/>
</bean> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:validmessages"/>
<property name="fileEncodings" value="utf-8"/>
<property name="cacheSeconds" value="120"/>
</bean> <!-- 以下 validator ConversionService 在使用 mvc:annotation-driven 会 自动注册-->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<!-- 如果不加默认到 使用classpath下的 ValidationMessages.properties -->
<property name="validationMessageSource" ref="messageSource" />
</bean> <mvc:annotation-driven validator="validator"/>
</beans>
@Valid springMVC bean校验不起作用的更多相关文章
- @Valid springMVC bean校验不起作用及如何统一处理校验
SpringMVC 使用JSR-303进行校验 @Valid 使用注解 一.准备校验时使用的JAR validation-api-1.0.0.GA.jar:JDK的接口: hibernate-vali ...
- @Valid注解的使用springmvc pojo校验
@Valid注解用于校验,所属包为:javax.validation.Valid. ① 首先需要在实体类的相应字段上添加用于充当校验条件的注解,如:@Min,如下代码(age属于User类中的属性): ...
- SpringMVC数据校验并通过国际化显示错误信息
目录 SpringMVC数据校验并通过国际化显示错误信息 SpringMVC数据校验 在页面中显示错误信息 通过国际化显示错误信息 SpringMVC数据校验并通过国际化显示错误信息 SpringMV ...
- SpringMVC参数校验(针对`@RequestBody`返回`400`)
SpringMVC参数校验(针对@RequestBody返回400) 前言 习惯别人帮忙做事的结果是自己不会做事了.一直以来,spring帮我解决了程序运行中的各种问题,我只要关心我的业务逻辑,设计好 ...
- 《Java从入门到放弃》入门篇:springMVC数据校验
昨天我们扯完了数据传递,今天我们来聊聊数据校验的问题.来,跟着我一起读:计一噢叫,一按艳. 在springMVC中校验数据也非常简单,spring3.0拥有自己独立的数据校验框架,同时支持JSR303 ...
- SpringMVC学习--校验
简介 项目中,通常使用较多是前端的校验,比如页面中js校验.对于安全要求较高点建议在服务端进行校验. 服务端校验: 控制层conroller:校验页面请求的参数的合法性.在服务端控制层conrolle ...
- SpringMVC参数校验
使用SpringMVC时配合hibernate-validate进行参数的合法性校验,能节省一定的代码量. 使用步骤 1.搭建Web工程并引入hibernate-validate依赖 <depe ...
- SpringMVC 数据校验(JSR-303)
项目中,通常使用较多的是前端的校验,比如页面中js校验以及form表单使用bootstrap校验.然而对于安全要求较高点建议在服务端进行校验. 服务端校验: 控制层controller:校验页面请求的 ...
- 关于 Spring Boot 中创建对象的疑虑 → @Bean 与 @Component 同时作用同一个类,会怎么样?
开心一刻 今天放学回家,气愤愤地找到我妈 我:妈,我们班同学都说我五官长得特别平 妈:你小时候爱趴着睡觉 我:你怎么不把我翻过来呢 妈:那你不是凌晨2点时候出生的吗 我:嗯,凌晨2点出生就爱趴着睡觉呗 ...
随机推荐
- 必须Mark!43个优秀的Swift开源项目推荐
摘要:拥有着苹果先天生态优势的Swift自发布以来,各种优秀的开源项目便层出不穷.本文作者站在个人的角度,将2014年Swift开源项目做了一个甄别.筛选,从工具.存储.网络.界面.框架到Demo以及 ...
- kindle相关工具
里是与 Kindle 电子书相关的工具软件.它们可以帮助我们解决在日常使用电子书时所可能遇到的问题,比如 kindle 管理工具.kindle 转换工具.kindle电子书制作工具.kindle 推送 ...
- JaxWsDynamicClientFactory弃用了,改成org.codehaus.xfire.client;
搞了好几天jar包冲突,最后修改接口调用方式 java.lang.IllegalStateException: Unable to create JAXBContext for generated p ...
- DataRow[] 转为数组
DataRow[] rows = dt.Select("1=1"); ].ToString()).ToArray();
- SQL Server 2008中SQL增强之三:Merge(在一条语句中使用Insert,Update,Delete) 一条语句实现两表同步(添加、删除、修改)
MERGE 目标表 USING 源表 ON 匹配条件 WHEN MATCHED THEN 语句 WHEN NOT MATCHED THEN 语句; http://www.chinaz.com/prog ...
- phpstorm laravel单元测试 配置
laravel中集成了单元测试工具phpunit可以在项目的根目录下进行使用,命令是:phpunti ./tests/单元测试文件名称.在phpstorm中使用phpunit需要做一些配置,指定com ...
- JDBC的URL设置allowMultiQueries的原因
如下的一个普通JDBC示例: String user ="root";String password = "root";String url = "j ...
- IntelliJ IDEA中怎么查看文件中所有方法?
可以使用快捷键ALT + 7打开左侧的Structure查看当前文件中的所有方法. 来自为知笔记(Wiz)
- android学习笔记36——使用原始XML文件
XML文件 android中使用XML文件,需要开发者手动创建res/xml文件夹. 实例如下: book.xml==> <?xml version="1.0" enc ...
- [Freescale]Freescale L3.14.52_1.1.0 yocto build
可参照:http://blog.csdn.net/wince_lover/article/details/51456745 1. Refer to <基于i.mx6处理器的Yocto项目及Lin ...