@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点出生就爱趴着睡觉呗 ...
随机推荐
- Asianux3配置yum
把下面四个文件放到/etc/yum.repos.d目录下 dag.repo: [dag] name=Dag RPM Repository for RHEL5 baseurl=http://mirror ...
- eclipse 怎么新建工作空间workspace
打开eclipse 点击文件“File”菜单切换工作空间“Switch Workspace”>其它“Other” 点击“Browser”选择新的工作空间目录. 选择新的工作空间目录,点击确定. ...
- web.xml中contextConfigLocation的作用
如果在web.xml里给该Listener指定要加载的xml,如: xml代码如下: <!-- spring config --> <context-param> <pa ...
- 删除Android自带软件方法及adb remount 失败解决方案
删除Android自带软件方法 1.在电脑上打开cmd,然后输入命令 adb remount adb shell su 2.接着就是Linux命令行模式了,输入 cd system/app 3然后输入 ...
- HTML 文本格式化
HTML 可定义很多供格式化输出的元素,比如粗体和斜体字. 下面有很多例子,您可以亲自试试: HTML 文本格式化实例 文本格式化 此例演示如何在一个 HTML 文件中对文本进行格式化 预格式文本 此 ...
- phonegap 2.7 ios配置安装详细教程(2.9通用)
原地址:http://www.cnblogs.com/yansi/archive/2013/05/14/3078222.html 在移动开发日益激烈的情况下我也不得不硬着头皮尝试下新鲜的html5的a ...
- 剑指offer系列46---和为s的连续正数序列
[题目]输出所有和为S的连续正数序列.序列为:1,2,3,4,5,6,7,8................ * 序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序 package com.e ...
- 黄聪:HtmlAgilityPack,C#实用的HTML解析类简介
HtmlAgilityPack是.net下的一个HTML解析类库.支持用XPath来解析HTML.这个意义不小,为什么呢?因为对于页面上的元素的xpath某些强大的浏览器能够直接获取得到,并不需要手动 ...
- (C#) 创建单元测试(Unit Test).
在VS2012中的右键中没有发现"Create Unit Test" 选项,原来需要安装个补丁: https://visualstudiogallery.msdn.microsof ...
- PL/SQL中批量执行SQL脚本(不可把所有的语句都复制到New SQL Windows)
PL/SQL中批量执行SQL脚本,不可把所有的语句都复制到New SQL Window,因为这样会导致缓冲区过大而进程卡死! 最好的办法是将要执行的SQL脚本存放到指定文件中,如C:\insert.s ...