本文主要是介绍Spring中使用JSR303进行数据校验,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
刚做完spring的Validator校验,紧接着做spring的JSR303校验,做完后发现差别不是非常大。废话不说,先来项目结构和jar包
1.项目结构和jar包
2.注册页registerForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试JSR303</title>
</head>
<body>
<!-- 本页面是一个注册页面,用于提交用户注册信息,之后将在后台使用JSR303进行验证 -->
<h3>注册页面</h3>
<form:form modelAttribute="user" method="post" action="login">
<table>
<tr>
<td>登录名:</td>
<td><form:input path="loginname"/></td>
<td><form:errors path="loginname" cssStyle="color:red"/> </td>
</tr>
<tr>
<td>密码:</td>
<td><form:input path="password"/></td>
<td><form:errors path="password" cssStyle="color:red"/> </td>
</tr>
<tr>
<td>用户名:</td>
<td><form:input path="username"/></td>
<td><form:errors path="username" cssStyle="color:red"/> </td>
</tr>
<tr>
<td>年龄:</td>
<td><form:input path="age"/></td>
<td><form:errors path="age" cssStyle="color:red"/> </td>
</tr>
<tr>
<td>邮箱:</td>
<td><form:input path="email"/></td>
<td><form:errors path="email" cssStyle="color:red"/> </td>
</tr>
<tr>
<td>生日:</td>
<td><form:input path="birthday"/></td>
<td><form:errors path="birthday" cssStyle="color:red"/> </td>
</tr>
<tr>
<td>电话:</td>
<td><form:input path="phone"/></td>
<td><form:errors path="phone" cssStyle="color:red"/> </td>
</tr>
<tr>
<td><input type="submit"/></td>
</tr>
</table>
</form:form>
</body>
</html>
3.实体类User.java
package org.fkit.domain;
import java.util.Date;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.Range;
import org.springframework.format.annotation.DateTimeFormat;
public class User {
@NotBlank(message="登录名不能为空")
private String loginname;
@NotBlank(message="密码不能为空")
@Length(min=6,max=8,message="密码长度必须在6~8位之间")
private String password;
@NotBlank(message="用户名不能为空")
private String username;
@Range(min=15,max=60,message="年龄必须在15~60岁之间")
private int age;
@Email(message="必须是合法的邮箱地址")
private String email;
@DateTimeFormat(pattern="yyyy-mm-dd")
private Date birthday;
@Pattern(regexp="[1][3,8][3,6,9][0-9]{8}",message="无效的电话号码")
private String phone;
//省略set和get方法…
}
4.控制器UserController.java
package org.fkit.controller;
import javax.validation.Valid;
import org.fkit.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class UserController {
@RequestMapping(value="/{formName}")
public String loginForm(@PathVariable String formName,Model model){
/**
* 这里要注意的是,因为jsp页面中绑定了名为user 的对象,
* 所以我们必须在这里提供一个User对象并放在域中,否则会报IllegalStateException异常,下同。
* */
User user = new User();
model.addAttribute("user", user);
//动态跳转页面
return formName;
}
//数据校验使用@Valid,后面跟着Errors对象保存校验信息
@RequestMapping(value="/login",method=RequestMethod.POST)
public String login(@Valid @ModelAttribute User user,
Errors errors,Model model) {
//如果errors中有错, 则返回注册页
if(errors.hasErrors()) {
return "registerForm";
}
//否则跳转到成功页
model.addAttribute("user", user);
return "success";
}
}
5.成功页success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试JSR303</title>
</head>
<body>
<h3>测试JSR303</h3>
登录名:${requestScope.user.loginname }<br>
密码:${requestScope.user.password }<br>
用户名:${requestScope.user.username }<br>
年龄:${requestScope.user.age }<br>
邮箱:${requestScope.user.email }<br>
生日:${requestScope.user.birthday }<br>
电话:${requestScope.user.phone }
</body>
</html>
6.配置文件
springmvc-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://mybatis.org/schema/mybatis-spring
http://mybatis.org/schema/mybatis-spring.xsd">
<!-- 自动扫描该包,SpringMVC会将包下用@Controller注解的类注册为Spring的controller -->
<context:component-scan base-package="org.fkit"/>
<!-- 设置默认配置方案 -->
<!-- 该标签会默认装配很多东西,其中有装配了LocalValidatorFactoryBean,因此不需要额外的配置 -->
<mvc:annotation-driven/>
<!-- 视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix">
<value>/WEB-INF/content/</value>
</property>
<!-- 后缀 -->
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>JSR303Test</display-name>
<!-- 定义Spring MVC的前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 让Spring MVC的前端控制器拦截所有请求 -->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 编码过滤器 -->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
小结:只要细心点,然后跟着书上来,理论上是不会错了。这次的代码中我遇到了一个错误:
Caused by: java.lang.NoClassDefFoundError: javax/validation/ParameterNameProvider
去网上查了一下,说的是包不匹配,具体如下:
所以呢, 遇到错误,如果没有思路,那么马上百度才是最省时间的做法。
================================================================
================================================================
以下是用maven进行实现相同的功能。
首先看一下项目结构:
-------------------------------------------------------
2.由于是一个例子,所以其代码可以说完全一样,只不过jar包交由maven管理罢了。
pom.xml
<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.lin</groupId><artifactId>JSR303_MavenTest</artifactId><version>0.0.1-SNAPSHOT</version><packaging>war</packaging><dependencies> <!-- spring begin --> <!--spring-core--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.2.0.RELEASE</version> </dependency> <!-- spring-web-mvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.2.0.RELEASE</version> </dependency> <!-- spring end --> <!-- Hibernate Validator Begin --><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-validator</artifactId><version>5.2.4.Final</version></dependency> <!-- <dependency><groupId>org.hibernate</groupId><artifactId>hibernate-validator-cdi</artifactId><version>6.0.7.Final</version></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-validator-annotation-processor</artifactId><version>6.0.7.Final</version></dependency> --><!-- Hibernate Validator End --><!-- jstl begin--><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><dependency><groupId>taglibs</groupId><artifactId>standard</artifactId><version>1.1.2</version></dependency><!-- jstl end --></dependencies> <!-- 添加项目jdk编译插件 --> <build> <!-- 设置编译版本为1.8 --> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> <!-- 配置tomcat7的插件,如果使用maven的命令方式运行,则命令为:tomcat7:run , 而不能是tomcat:run(如果使用该命令,还是会使用maven默认的tomcat来编译运行项目)。 可以直接使用eclipse中的tomcat来运行项目(就是原先没有使用maven时的那样运行项目就可以了,那样的话也不需要配这个插件了)。 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.1</version> </plugin> </plugins> </build>
</project>
----------------------------------------------------------------------------
其他重复代码不再粘贴,项目依旧可以跑得起来……(今天来复用代码的时候出现了点问题,上面测试的环境是jdk1.8+tomcat8.5。。。然后我今天用公司的jdk1.7+tomcat7.0就跑不动。目前猜测是tomcat的问题。。。)
这篇关于Spring中使用JSR303进行数据校验的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!