spring mvc 使用jsr-303进行表单验证的方法介绍
源代码来源:http://howtodoinjava.com/spring/spring-mvc/spring-bean-validation-example-with-jsr-303-annotations/,原文解释的更加清楚。此文主要是为了理顺整个项目的构建过程。



<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.howtodoinjava.mvc</groupId>
<artifactId>jsr303Demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging> <dependencies>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.1.Final</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency> <!-- Spring MVC support --> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.4.RELEASE</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.4.RELEASE</version>
</dependency> <!-- Tag libs support for view layer --> <dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>runtime</scope>
</dependency> <dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
package com.howtodoinjava.demo.model; import java.io.Serializable; import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size; public class EmployeeVO implements Serializable
{
private static final long serialVersionUID = 1L; private Integer id; @Size(min = 3, max = 20)
private String firstName; @Size(min = 3, max = 20)
private String lastName; @Pattern(regexp=".+@.+\\.[a-z]+")
private String email; //Setters and Getters
public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getFirstName() {
return firstName;
} public void setFirstName(String firstName) {
this.firstName = firstName;
} public String getLastName() {
return lastName;
} public void setLastName(String lastName) {
this.lastName = lastName;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} @Override
public String toString() {
return "EmployeeVO [id=" + id + ", firstName=" + firstName
+ ", lastName=" + lastName + ", email=" + email + "]";
}
}
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Spring Web MVC Hello World Application</display-name> <servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> </web-app>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
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"> <context:component-scan base-package="com.howtodoinjava.demo" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean> <bean class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean> </beans>
package com.howtodoinjava.demo.controller; import java.util.Set; import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus; import com.howtodoinjava.demo.model.EmployeeVO;
import com.howtodoinjava.demo.service.EmployeeManager; @Controller
@RequestMapping("/employee-module/addNew")
@SessionAttributes("employee")
public class EmployeeController {
@Autowired
EmployeeManager manager; private Validator validator; public EmployeeController()
{
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
validator = validatorFactory.getValidator();
} @RequestMapping(method = RequestMethod.GET)
public String setupForm(Model model) {
EmployeeVO employeeVO = new EmployeeVO();
model.addAttribute("employee", employeeVO);
return "addEmployee";
} @RequestMapping(method = RequestMethod.POST)
public String submitForm(@ModelAttribute("employee") EmployeeVO employeeVO,
BindingResult result, SessionStatus status) { Set<ConstraintViolation<EmployeeVO>> violations = validator.validate(employeeVO); for (ConstraintViolation<EmployeeVO> violation : violations)
{
String propertyPath = violation.getPropertyPath().toString();
String message = violation.getMessage();
// Add JSR-303 errors to BindingResult
// This allows Spring to display them in view via a FieldError
result.addError(new FieldError("employee",propertyPath, "Invalid "+ propertyPath + "(" + message + ")"));
} if (result.hasErrors()) {
return "addEmployee";
}
// Store the employee information in database
// manager.createNewRecord(employeeVO); // Mark Session Complete
status.setComplete();
return "redirect:addNew/success";
} @RequestMapping(value = "/success", method = RequestMethod.GET)
public String success(Model model) {
return "addSuccess";
}
}
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> <html>
<head>
<title>Add Employee Form</title>
</head> <body>
<h2><spring:message code="lbl.page" text="Add New Employee" /></h2>
<br/>
<form:form method="post" modelAttribute="employee">
<table>
<tr>
<td><spring:message code="lbl.firstName" text="First Name" /></td>
<td><form:input path="firstName" /></td>
<td><form:errors path="firstName" cssClass="error" /></td>
</tr>
<tr>
<td><spring:message code="lbl.lastName" text="Last Name" /></td>
<td><form:input path="lastName" /></td>
<td><form:errors path="lastName" cssClass="error" /></td>
</tr>
<tr>
<td><spring:message code="lbl.email" text="Email Id" /></td>
<td><form:input path="email" /></td>
<td><form:errors path="email" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Add Employee"/></td>
</tr>
</table>
</form:form>
</body>
</html>
<html>
<head>
<title>Add Employee Success</title>
</head>
<body>
Employee has been added successfully.
</body>
</html>

spring mvc 使用jsr-303进行表单验证的方法介绍的更多相关文章
- Spring Boot 2 + Thymeleaf:服务器端表单验证
表单验证分为前端验证和服务器端验证.服务器端验证方面,Java提供了主要用于数据验证的JSR 303规范,而Hibernate Validator实现了JSR 303规范.项目依赖加入spring-b ...
- spring boot学习(7) SpringBoot 之表单验证
第一节:SpringBoot 之表单验证@Valid 是spring-data-jpa的功能: 下面是添加学生的信息例子,要求姓名不能为空,年龄大于18岁. 贴下代码吧: Student实体: ...
- AngularJS表单验证实现方法详解
本文主要是通过源码实例和大家分享AngularJS中的表单验证相关知识,希望通过本文的分享,对大家学习AngularJS有所帮助. 1.常规表单验证: 2.AngularJs中提供的表单验证实例. 实 ...
- [js]js的表单验证onsubmit方法
http://uule.iteye.com/blog/2183622 表单验证类 <form class="form" method="post" id= ...
- spring mvc Controller与jquery Form表单提交代码demo
1.JSP表单 <% String basePath = request.getScheme() + "://" + request.getServerName() +&qu ...
- Spring MVC 用post方式提交表单到Controller乱码问题,而get方式提交没有乱码问题
在web.xml中添加一个filter,即可解决post提交到Spring MVC乱码问题 <!-- 配置请求过滤器,编码格式设为UTF-8,避免中文乱码--> <filter> ...
- Spring Boot学习——表单验证
我觉得表单验证主要是用来防范小白搞乱网站和一些低级的黑客技术.Spring Boot可以使用注解 @Valid 进行表单验证.下面是一个例子. 例子说明:数据库增加一条Student记录,要求学生年龄 ...
- 再说表单验证,在Web Api中使用ModelState进行接口参数验证
写在前面 上篇文章中说到了表单验证的问题,然后尝试了一下用扩展方法实现链式编程,评论区大家讨论的非常激烈也推荐了一些很强大的验证插件.其中一位园友提到了说可以使用MVC的ModelState,因为之前 ...
- Laravel教程 七:表单验证 Validation
Laravel教程 七:表单验证 Validation 此文章为原创文章,未经同意,禁止转载. Laravel Form 终于要更新这个Laravel系列教程的第七篇了,期间去写了一点其他的东西. 就 ...
随机推荐
- PDO的事物处理机制
Mysql的事务处理: 1.MySQL目前只有InnoDB 和BDB两个数据表类型才支持事务. 2.在默认条件下,MySQL是以自动提交(autocommit)模式运行的,这就意味着所执行的每一个语句 ...
- Ubuntu root登陆
分两步: 1.激活root 输入命令:sudo passwd,键入当前用户密码之后,为系统设置root密码:交互如下: jack@ubuntu:~$ sudo passwd[sudo] passwor ...
- Oracle EBS-SQL (BOM-13):检查未定义库存分的物料类.sql
select distinct msi.segment1 编码 , msi.description 描述 , msi.primary_ ...
- ARM 7 用户模式下禁止/使能中断的一种方法--使用软中断 for Keil MDK
最近写一个程序,需要在用户模式下关中断,但ARM 7的体系结构决定了中断必须在特权模式下才可以更改,所以想到使用ARM的软中断来实现关中断和开中断. 使用软中断,首先要有硬件指令的支持.ARM有条指令 ...
- 提高mindmanager 8的启动速度
提高mindmanager 8的启动速度一连串 发布于:2010-01-13 18:12不少人抱怨mindmanager 8的启动速度较慢,用以下办法配置一下就能解决:1.进入mindmanager ...
- 攻击DotCom小游戏
许久都没写博客了,些许是前段时间有些懈怠,今天来写博客,想记录下做过的事情,怕以后电脑换了,以前做的小项目也跟着丢了,总结下最近做的一个小游戏: 游戏目的:建立一个7X7的网格,选择其中的连续的三格来 ...
- 转载: Nova-Router 分析
很早的实现了,nova代码已经做了很多修改了. 以创建实例 URL(http://10.191.7.32:8773/v1.1/service?*****)为例说明 Router 的执行流程 1. 依据 ...
- Ognl中根元素与非根元素的关系
Ognl中根元素与非根元素的关系 根元素:可以理解为全局变量 非根元素:局部变量 从两者获取其属性的方式看: Object obj = Ognl.parseExpression(“[1]”); [1] ...
- Curious Robin Hood(树状数组+线段树)
1112 - Curious Robin Hood PDF (English) Statistics Forum Time Limit: 1 second(s) Memory Limit: 64 ...
- MySQL存储过程的基本函数
(1).字符串类 CHARSET(str) //返回字串字符集 CONCAT (string2 [,... ]) //连接字串 INSTR (string ,substring ) //返回subst ...