1. @RequestMapping("/add2")
  2. public String addStudentValid(@Valid @ModelAttribute("s") Student s,BindingResult result){
  3. if(result.hasErrors()){
  4. List<FieldError> fieldErrors = result.getFieldErrors();
  5.  
  6. for (FieldError fieldError : fieldErrors) {
  7. log.info("errors --"+fieldError.getField()+fieldError.getDefaultMessage());
  8. }
  9. }
  10. log.info("s.name="+s.getName());
  11. log.info("s.age="+s.getAge());
  12. return "success";
  13. }
  1. import javax.validation.constraints.Min;
  2. import org.hibernate.validator.constraints.Length;
  3. import org.hibernate.validator.constraints.NotEmpty;
  4.  
  5. public class Student {
  6.  
  7. @NotEmpty
  8. @Length(min=4,message="{stu.name}")
  9. private String name;
  10. @Min(value=18,message="{stu.age}")
  11. private int age;
  12. public String getName() {
  13. return name;
  14. }
  15. public void setName(String name) {
  16. this.name = name;
  17. }
  18. public int getAge() {
  19. return age;
  20. }
  21. public void setAge(int age) {
  22. this.age = age;
  23. }
  24.  
  25. @Override
  26. public String toString() {
  27. return "toString - name="+name+";age="+age;
  28. }
  29.  
  30. }

需要开启注解 <mvc:annotation-driven/>才能启用验证。否则@valid不管用。

  1. 如果要使用错误提示的国际化消息,如stu.nameproperties文件中的键值对
    @Length(min=4,message="{stu.name}")

则需要在dispatcher-servlet.xml中配置

  1. <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
  2. <property name="basename" value="classpath:validmessages"/>
  3. <property name="fileEncodings" value="utf-8"/>
  4. <property name="cacheSeconds" value="120"/>
  5. </bean>
  6.  
  7. <!-- 以下 validator ConversionService 在使用 mvc:annotation-driven 会 自动注册-->
  8. <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
  9. <property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
  10. <!-- 如果不加默认到 使用classpath下的 ValidationMessages.properties -->
  11. <property name="validationMessageSource" ref="messageSource" />
  12. </bean>
  13.  
  14. <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为

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:p="http://www.springframework.org/schema/p"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:mvc="http://www.springframework.org/schema/mvc"
  7. xmlns:tx="http://www.springframework.org/schema/tx"
  8. xsi:schemaLocation="
  9. http://www.springframework.org/schema/beans
  10. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  11. http://www.springframework.org/schema/context
  12. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  13. http://www.springframework.org/schema/mvc
  14. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
  15. http://www.springframework.org/schema/tx
  16. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  17. ">
  18.  
  19. <context:component-scan base-package="com.upper"/>
  20.  
  21. <!-- freemarker的配置 -->
  22. <bean id="freemarkerConfigurer"
  23. class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
  24. <property name="templateLoaderPath" value="/WEB-INF/views/" />
  25. <property name="defaultEncoding" value="GBK" />
  26. <property name="freemarkerSettings">
  27. <props>
  28. <prop key="template_update_delay">0</prop>
  29. <prop key="locale">zh_CN</prop>
  30. <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
  31. <prop key="date_format">yyyy-MM-dd</prop>
  32. <prop key="number_format">#.##</prop>
  33. <!-- <prop key="auto_import">c_index.tpl as p</prop> -->
  34. </props>
  35. </property>
  36. </bean>
  37. <!-- FreeMarker视图解析 如返回userinfo。。在这里配置后缀名ftl和视图解析器。。 -->
  38. <bean id="viewResolver"
  39. class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
  40. <property name="viewClass"
  41. value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" />
  42. <property name="suffix" value=".ftl" />
  43. <property name="contentType" value="text/html;charset=GBK" />
  44. <property name="exposeRequestAttributes" value="true" />
  45. <property name="exposeSessionAttributes" value="true" />
  46. <property name="exposeSpringMacroHelpers" value="true" />
  47. <property name="requestContextAttribute" value="rc" />
  48. <property name="allowSessionOverride" value="true"/>
  49. </bean>
  50.  
  51. <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
  52. <property name="basename" value="classpath:validmessages"/>
  53. <property name="fileEncodings" value="utf-8"/>
  54. <property name="cacheSeconds" value="120"/>
  55. </bean>
  56.  
  57. <!-- 以下 validator ConversionService 在使用 mvc:annotation-driven 会 自动注册-->
  58. <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
  59. <!-- 如果不加默认到 使用classpath下的 ValidationMessages.properties -->
  60. <property name="validationMessageSource" ref="messageSource" />
  61. </bean>
  62.  
  63. <mvc:annotation-driven validator="validator"/>
  64. </beans>

@Valid springMVC bean校验不起作用的更多相关文章

  1. @Valid springMVC bean校验不起作用及如何统一处理校验

    SpringMVC 使用JSR-303进行校验 @Valid 使用注解 一.准备校验时使用的JAR validation-api-1.0.0.GA.jar:JDK的接口: hibernate-vali ...

  2. @Valid注解的使用springmvc pojo校验

    @Valid注解用于校验,所属包为:javax.validation.Valid. ① 首先需要在实体类的相应字段上添加用于充当校验条件的注解,如:@Min,如下代码(age属于User类中的属性): ...

  3. SpringMVC数据校验并通过国际化显示错误信息

    目录 SpringMVC数据校验并通过国际化显示错误信息 SpringMVC数据校验 在页面中显示错误信息 通过国际化显示错误信息 SpringMVC数据校验并通过国际化显示错误信息 SpringMV ...

  4. SpringMVC参数校验(针对`@RequestBody`返回`400`)

    SpringMVC参数校验(针对@RequestBody返回400) 前言 习惯别人帮忙做事的结果是自己不会做事了.一直以来,spring帮我解决了程序运行中的各种问题,我只要关心我的业务逻辑,设计好 ...

  5. 《Java从入门到放弃》入门篇:springMVC数据校验

    昨天我们扯完了数据传递,今天我们来聊聊数据校验的问题.来,跟着我一起读:计一噢叫,一按艳. 在springMVC中校验数据也非常简单,spring3.0拥有自己独立的数据校验框架,同时支持JSR303 ...

  6. SpringMVC学习--校验

    简介 项目中,通常使用较多是前端的校验,比如页面中js校验.对于安全要求较高点建议在服务端进行校验. 服务端校验: 控制层conroller:校验页面请求的参数的合法性.在服务端控制层conrolle ...

  7. SpringMVC参数校验

    使用SpringMVC时配合hibernate-validate进行参数的合法性校验,能节省一定的代码量. 使用步骤 1.搭建Web工程并引入hibernate-validate依赖 <depe ...

  8. SpringMVC 数据校验(JSR-303)

    项目中,通常使用较多的是前端的校验,比如页面中js校验以及form表单使用bootstrap校验.然而对于安全要求较高点建议在服务端进行校验. 服务端校验: 控制层controller:校验页面请求的 ...

  9. 关于 Spring Boot 中创建对象的疑虑 → @Bean 与 @Component 同时作用同一个类,会怎么样?

    开心一刻 今天放学回家,气愤愤地找到我妈 我:妈,我们班同学都说我五官长得特别平 妈:你小时候爱趴着睡觉 我:你怎么不把我翻过来呢 妈:那你不是凌晨2点时候出生的吗 我:嗯,凌晨2点出生就爱趴着睡觉呗 ...

随机推荐

  1. Asianux3配置yum

    把下面四个文件放到/etc/yum.repos.d目录下 dag.repo: [dag] name=Dag RPM Repository for RHEL5 baseurl=http://mirror ...

  2. eclipse 怎么新建工作空间workspace

    打开eclipse 点击文件“File”菜单切换工作空间“Switch Workspace”>其它“Other” 点击“Browser”选择新的工作空间目录. 选择新的工作空间目录,点击确定. ...

  3. web.xml中contextConfigLocation的作用

    如果在web.xml里给该Listener指定要加载的xml,如: xml代码如下: <!-- spring config --> <context-param> <pa ...

  4. 删除Android自带软件方法及adb remount 失败解决方案

    删除Android自带软件方法 1.在电脑上打开cmd,然后输入命令 adb remount adb shell su 2.接着就是Linux命令行模式了,输入 cd system/app 3然后输入 ...

  5. HTML 文本格式化

    HTML 可定义很多供格式化输出的元素,比如粗体和斜体字. 下面有很多例子,您可以亲自试试: HTML 文本格式化实例 文本格式化 此例演示如何在一个 HTML 文件中对文本进行格式化 预格式文本 此 ...

  6. phonegap 2.7 ios配置安装详细教程(2.9通用)

    原地址:http://www.cnblogs.com/yansi/archive/2013/05/14/3078222.html 在移动开发日益激烈的情况下我也不得不硬着头皮尝试下新鲜的html5的a ...

  7. 剑指offer系列46---和为s的连续正数序列

    [题目]输出所有和为S的连续正数序列.序列为:1,2,3,4,5,6,7,8................ * 序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序 package com.e ...

  8. 黄聪:HtmlAgilityPack,C#实用的HTML解析类简介

    HtmlAgilityPack是.net下的一个HTML解析类库.支持用XPath来解析HTML.这个意义不小,为什么呢?因为对于页面上的元素的xpath某些强大的浏览器能够直接获取得到,并不需要手动 ...

  9. (C#) 创建单元测试(Unit Test).

    在VS2012中的右键中没有发现"Create Unit Test" 选项,原来需要安装个补丁: https://visualstudiogallery.msdn.microsof ...

  10. PL/SQL中批量执行SQL脚本(不可把所有的语句都复制到New SQL Windows)

    PL/SQL中批量执行SQL脚本,不可把所有的语句都复制到New SQL Window,因为这样会导致缓冲区过大而进程卡死! 最好的办法是将要执行的SQL脚本存放到指定文件中,如C:\insert.s ...