http://www.mkyong.com/spring-mvc/spring-3-mvc-and-jsr303-valid-example/

————————————————————————————————————————————————————————

用jsr303验证表单数据,搞了很长时间,验证倒是验证了,但是@Valid不起作用,表现是:

无论是否加@Valid, 都会验证,并且spring无法捕获到异常BindingResult.hasErrors始终是false。

上面那个例子就可以。具体原因还不是很明了,按上面那个例子,对有问题的项目做如下处理:

1 使用<mvc:annotation-driven />

2 去掉DefaultAnnotationHandlerMapping, ControllerClassNameHandlerMapping, AnnotationMethodHandlerAdapter

3 因为去掉了ControllerClassNameHandlerMapping,在控制器做相应处理

————————————————————————————

现在想想之前尝试各种办法都不成功,有没有可能跟这个异常有关系呢?应该没有,之前应该已经尝试过这种情况。

Caused by: java.lang.OutOfMemoryError: PermGen space

————————————————————————————————————————————————————————

In Spring 3, you can enable “mvc:annotation-driven” to support JSR303 bean validation via @Valid annotation, if any JSR 303 validator framework on the classpath.

Note
Hibernate Validator is the reference implementation for JSR 303

In this tutorial, we show you how to integrate Hibernate validator with Spring MVC, via @Valid annotation, to perform bean validation in a HTML form.

Technologies used :

  1. Spring 3.0.5.RELEASE
  2. Hibernate Validator 4.2.0.Final
  3. JDK 1.6
  4. Eclipse 3.6
  5. Maven 3

1. Project Dependencies

Hibernate validator is available at JBoss public repository.

    <repositories>
<repository>
<id>JBoss repository</id>
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
</repositories> <properties>
<spring.version>3.0.5.RELEASE</spring.version>
</properties> <dependencies> <!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency> <!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency> </dependencies>

2. JSR303 Bean Validation

A simple POJO, annotated with Hibernate validator annotation.

Note
Refer to this Hibernate validator documentation for detail explanation
package com.mkyong.common.model;

import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range; public class Customer { @NotEmpty //make sure name is not empty
String name; @Range(min = 1, max = 150) //age need between 1 and 150
int age; //getter and setter methods }

3. Controller + @Valid

For validation to work, just annotate the “JSR annotated model object” via @Valid. That’s all, other stuff is just a normal Spring MVC form handling.

package com.mkyong.common.controller;

import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.mkyong.common.model.Customer; @Controller
@RequestMapping("/customer")
public class SignUpController { @RequestMapping(value = "/signup", method = RequestMethod.POST)
public String addCustomer(@Valid Customer customer, BindingResult result) { if (result.hasErrors()) {
return "SignUpForm";
} else {
return "Done";
} } @RequestMapping(method = RequestMethod.GET)
public String displayCustomerForm(ModelMap model) { model.addAttribute("customer", new Customer());
return "SignUpForm"; } }

4. Error Message

By default, if validation failed.

  1. @NotEmpty will display “may not be empty”
  2. @Range will display “must be between 1 and 150″

You can override it easily, create a properties with “key” and message. To know which @annotation bind to which key, just debug it and view value inside “BindingResult result“. Normally, the key is “@Annotation Name.object.fieldname“.

File : messages.properties

NotEmpty.customer.name = Name is required!
Range.customer.age = Age value must be between 1 and 150

5. mvc:annotation-driven

Enable “mvc:annotation-driven” to make Spring MVC supports JSR303 validator via @Valid, and also bind your properties file.

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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-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"> <context:component-scan base-package="com.mkyong.common.controller" /> <!-- support JSR303 annotation if JSR 303 validation present on classpath -->
<mvc:annotation-driven /> <bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean> <!-- bind your messages.properties -->
<bean class="org.springframework.context.support.ResourceBundleMessageSource"
id="messageSource">
<property name="basename" value="messages" />
</bean> </beans>

6. JSP Pages

Last one, normal JSP page with Spring form tag library.

File : SignUpForm.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<style>
.error {
color: #ff0000;
} .errorblock {
color: #000;
background-color: #ffEEEE;
border: 3px solid #ff0000;
padding: 8px;
margin: 16px;
}
</style>
</head> <body>
<h2>Customer SignUp Form - JSR303 @Valid example</h2> <form:form method="POST" commandName="customer" action="customer/signup">
<form:errors path="*" cssClass="errorblock" element="div" />
<table>
<tr>
<td>Customer Name :</td>
<td><form:input path="name" /></td>
<td><form:errors path="name" cssClass="error" /></td>
</tr>
<tr>
<td>Customer Age :</td>
<td><form:input path="age" /></td>
<td><form:errors path="age" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form> </body>
</html>

File : Done.jsp

<html>
<body>
<h2>Done</h2>
</body>
</html>

6. Demo

URL : http://localhost:8080/SpringMVC/customer – Customer form page, with 2 text boxes for name and age.

URL : http://localhost:8080/SpringMVC/customer/signup – If you didn’t fill in the form and click on the “submit” button, your customized validation error messages will be displayed.

Download Source Code

References

  1. Spring JSR303 validation documentation
  2. JSR303 bean validation
  3. Hibernate Validator

Spring 3 MVC and JSR303 @Valid example的更多相关文章

  1. spring 3 mvc hello world + mavern +jetty

    Spring 3 MVC hello world example By mkyong | August 2, 2011 | Updated : June 15, 2015 In this tutori ...

  2. Spring MVC 数据校验@Valid

    先看看几个关键词 @Valid @Pattern @NotNull @NotBlank @Size BindingResult 这些就是Spring MVC的数据校验的几个注解. 那怎么用呢?往下看 ...

  3. spring mvc 使用jsr-303进行表单验证的方法介绍

    源代码来源:http://howtodoinjava.com/spring/spring-mvc/spring-bean-validation-example-with-jsr-303-annotat ...

  4. Spring - Sring MVC入门

    2.1.Spring Web MVC是什么 Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职 ...

  5. Spring 4 MVC+Hibernate 4+MySQL+Maven使用注解集成实例

    Spring 4 MVC+Hibernate 4+MySQL+Maven使用注解集成实例 转自:通过注解的方式集成Spring 4 MVC+Hibernate 4+MySQL+Maven,开发项目样例 ...

  6. Spring Web MVC框架简介

    Web MVC framework框架 Spring Web MVC框架简介 Spring MVC的核心是`DispatcherServlet`,该类作用非常多,分发请求处理,配置处理器映射,处理视图 ...

  7. Spring Framework------>version4.3.5.RELAESE----->Reference Documentation学习心得----->Spring Framework中的spring web MVC模块

    spring framework中的spring web MVC模块 1.概述 spring web mvc是spring框架中的一个模块 spring web mvc实现了web的MVC架构模式,可 ...

  8. Spring Web MVC(三)之注解

    [toc] spring web mvc 基于注解的优化 我写的注解是按照spring web的部件分类写的,这样的话比较方便查看,大家感觉有用的话可以分享个别人,希望对对更多的人有帮助.毕竟零基础开 ...

  9. 菜鸟学习Spring Web MVC之二

    有文章从结构上详细讲解了Spring Web MVC,我个菜鸟就不引据来讲了.说说强悍的XP环境如何配置运行环境~~ 最后我配好的环境Tomcat.Spring Tool Suites.Maven目前 ...

随机推荐

  1. java中的注解详解和自定义注解

    一.java中的注解详解 1.什么是注解 用一个词就可以描述注解,那就是元数据,即一种描述数据的数据.所以,可以说注解就是源代码的元数据.比如,下面这段代码: @Override public Str ...

  2. SqlServer_合并多个递归查询数据(CTE)

    该方法在数据量过大时,效率过低,可参考hierarchyid字段实现(Sqlserver 2008) 优点:效率较高 缺点:需要不断维护数据,对现有业务有一定影响 参考:http://www.cnbl ...

  3. mysql group_concat函数

    函数语法: group_concat( [DISTINCT] 要连接的字段 [Order BY 排序字段 ASC/DESC] [Separator '分隔符'] ) 下面举例说明: select * ...

  4. 安装office2016 64位时提示64位与32位的office程序不兼容,在系统是64位的情况下,由于应用的需要,必须装64位的office,怎么办

    解决办法如下: 如果是,那就看看32位的能不能安装了,要是能,就重新安装一次,把所有组件全部安装,然后,在进行卸载,一般可以卸载成功 如果卸载不成功,这个时候再使用微软的专用卸载工具,——要认清,一定 ...

  5. nginx和selinux冲突

    cat /var/log/audit/audit.log |grep nginx |grep denied| audit2allow -M mynginx 取出selinux中有关于nginx被拒绝的 ...

  6. 对象内部属性[[Class]]

    1.概述 所有的typeof返回值为‘object’的对象都包含一个内部属性[[Class]],我们将它可以看做内部的分类,而非传统面向对象意义的分类.这个属性无法直接访问,一般通过Object.pr ...

  7. 自定义通用dialogFragment

    代码地址如下:http://www.demodashi.com/demo/12844.html 前言 之前写过一篇dialogFragmnet封装默认dialog的文章 DialogFragment创 ...

  8. iOS开发-自动布局之autoresizingMask使用详解(Storyboard&Code)

    前言:现在已经不像以前那样只有一个尺寸,现在最少的IPHONE开发需要最少需要适配三个尺寸.因此以前我们可以使用硬坐标去设定各个控件的位置,但是现在的话已经不可以了,我们需要去做适配,也许你说可以使用 ...

  9. UnicodeEncodeError: ‘gbk’ codec can’t encode character u’\u200e’ in position 43: illegal multibyte sequence

    [问题] python中已获取网页: http://blog.csdn.net/hfahe/article/details/5494895 的html源码,其时UTF-8编码的. 提取出其标题部分: ...

  10. tcp/ip ---以太网和IEEE 802封装

    以太网 它是当今T C P / I P采用的主要的局域网技术.它采用一种称作C S M A / C D的媒体接入方法,其意思是带冲突检测的载波侦听多路接入(Carrier Sense, Multipl ...