首页 > 代码库 > Spring MVC 数据验证——validate编码方式
Spring MVC 数据验证——validate编码方式
1、导入jar包
- validation-api-1.0.0.GA.jar这是比較关键的一个jar包,主要用于解析注解@Valid.
- hibernate-validator-4.3.2.Final.jar能够下载最新的。这个包在注解方式编码中尤为重要。
- 其它的就是一些日志包(不一定全不须要):jboss-logging-3.1.3.GA.jar、slf4j-log4j12-1.6.1.jar
2、web项目的结构图
项目的主要结构图,不清楚web项目的环境的能够自己学一下。推荐去慕课网上找视频看
lib库中的jar包,贴出来方便对比。主要有3个类:spring核心库、validate须要载入的库、其它库(这里有几个jsp标签库。不是重点)
3、项目配置
- web.xml配置
Spring mvc项目的最小配置
<?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" version="3.1">
<display-name>SpringMVC</display-name>
<welcome-file-list>
<welcome-file>jsp/hello.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
- hello-servlet.xml配置
通过自己主动载入
<?xml version="1.0" encoding="UTF-8"?
>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan
base-package="controller">
</context:component-scan>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp">
<!-- <property name="viewClass" value=http://www.mamicode.com/"org.springframework.web.servlet.view.JstlView"></property> -->
</bean>
<!--数据验证 编码方式的配置-->
<mvc:annotation-driven validator="accountValidator"/>
<bean id="accountValidator" class="dao.AccountValidator"></bean>
</beans>
4、src下加入源代码
- controller包
RegisterController类主要有两个方法,一个用于get,还有一个用于post。当中数据验证是放在registerIF()方法中的。验证是通过前两个參数。第一个參数是一个javabean保存的是注冊用户的信息,第二个參数用于数据验证提交过来的javabean对象。
package controller;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import dao.Account;
import dao.AccountValidator;
@Controller
@RequestMapping("/register")
public class RegisterController {
@RequestMapping(method=RequestMethod.GET)
public String register(Model model){
if (!model.containsAttribute("account")) {
model.addAttribute("account",new Account());
}
return "register";
}
@InitBinder
public void initBinder(DataBinder binder){
binder.setValidator(new AccountValidator());
}
@RequestMapping(method=RequestMethod.POST)
public String registerIF(@Valid @ModelAttribute("account")Account account,BindingResult result,Model model){
System.out.println("用户名:"+account.getUsername());
if (result.hasErrors()) {
System.out.println("register faliure.");
model.addAttribute("message", "注冊失败");
}else {
model.addAttribute("message", "注冊成功");
}
return "register";
}
}
- dao包
(1)、javabean类Account,用于保存注冊用户信息
package dao;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
public class Account {
private String username;
private String password;
public Account() {
// TODO Auto-generated constructor stub
}
public Account(String username, String password) {
super();
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
(2)、 AccountValidator用于检验Account的输入用户信息
这个就是编码方式验证数据的主要类,通过hello-servlet.xml中的自己主动载入方式,将类载入进去,引入点就是在@Valid注解处。
package dao;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class AccountValidator implements Validator {
@Override
public boolean supports(Class<?> arg0) {
// TODO Auto-generated method stub
return Account.class.equals(arg0);
}
@Override
//主要通过这种方法,验证数据
public void validate(Object obj, Errors erros) {
// TODO Auto-generated method stub
ValidationUtils.rejectIfEmpty(erros, "username", null,"用户名不能为空.");
ValidationUtils.rejectIfEmpty(erros, "password", null,"密码不能为空.");
Account account = (Account) obj;
if (account.getUsername().length()<3 || account.getUsername().length()>20) {
erros.rejectValue("username","length","用户名长度在3-20个字符串之间");
}
if (account.getPassword().length()<6 || account.getPassword().length()>20) {
erros.rejectValue("password","size","密码长度在6-20个字符之间");
}
}
}
5、加入jsp
在WEB-INF中新建一个jsp文件夹,然后新建一个register.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">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>注冊界面</title>
</head>
<body>
<form:form method="post" modelAttribute="account">
<label for="username">用户名:</label>
<form:input type="text" path="username"/>
<form:errors path="username"/><br><br>
<label for="pwd">密码:</label>
<form:input type="password" path="password"/>
<form:errors path="password"/>
<br><br>
<input type="submit" value="注冊" name="login"/>
</form:form>
<br><hr>
${message}
</body>
</html>
6、效果演示
执行程序,然后在浏览器中输入地址:http://localhost:8080/annotation_springmvc/register
Spring MVC 数据验证——validate编码方式