@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点出生就爱趴着睡觉呗 ...
随机推荐
- ASP.NET MVC 程序 报错“CS0012: 类型“System.Data.Objects.DataClasses.EntityObject”在未被引用的程序集中定义”的解决办法
运行MVC程序,具体报错信息如下: 解决方法: 打开Web.config在assemblies下加入<add assembly="System.Data.Entity, Version ...
- 数字根(digital root)
来源:LeetCode 258 Add Dights Question:Given a non-negative integer num , repeatedly add all its digi ...
- 如何通过SecureCRT FTP上传下载文件
通过SecureCRT FTP方式从一台机器下载文件到另一台机器上: [root@TEST144239 ~]# ftp 10.30.1.25 Connected to 10.30.1.25 (10. ...
- ShopEX 4.8.5.81822 前台Getshell
ShopEX 4.8.5.81822 前台Getshell 作者:unhonker 发布:2014-06-23 00:12 分类:漏洞公布 被撸:8,179次 抢沙发 利用方式 ...
- mootools里选择器$,$$,$E,$ES等的区别
区别就是 $和$$都是1个参数, $适用于ID,或者ID代表的对象 $$适用于CSS选择器 $E和$ES,有2个参数,第二个参数是可选参数代表(filter,即某个ID范围里的元素) $E('inpu ...
- 怎么利用WinPE恢复系统注册表?
我们的电脑总是会遇到各种各样的问题,最好用的方式就是电脑重装,重装系统的方式有很多,光盘安装.硬盘安装.U盘安装等.但是碰到电脑系统瘫痪无法启动,甚至连安全模式也进不了的时候,你的光盘.硬盘就没有用处 ...
- H5元素
下面整理下我用到的H5元素 placeholder 显示input输出口的默认提示文本 <input type="search" name="user_search ...
- HTTP头域列表与解释 之 request篇
HTTP 头域是HTTP协议中请求(request)和响应(response)中的头部信息,其实就是HTTP通信的操作参数,告诉web服务器和浏览器怎样处理这个通信.HTTP头从一个请求信息或者响应信 ...
- CSU 1803 2016(数论)
2016 Problem Description: 给出正整数 n 和 m,统计满足以下条件的正整数对 (a,b) 的数量: 1≤a≤n,1≤b≤m; a×b 是 2016 的倍数. Input: 输 ...
- SecureCRT 的安装和注册
基本信息:win764位 准备: 下载软件包:scrt70-x86.exe,和SecureCRT.7.3.keygen.exe注册机 下载地址:http://download.csdn.net/det ...