SpringMVC的数据校验

一.使用Spring的Validation校验

1.导入使用Spring需要导入的jar包

2.配置web.xml文件:配置前端控制器:



  SpringMVCValidation
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  
  
  springmvc
  org.springframework.web.servlet.DispatcherServlet
  
  	contextConfigLocation
  	classpath:springmvc.xml
  
  
  1
  
  
  springmvc
  *.action
  
3.编写视图:

loginForm.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>




测试Validator接口验证


登录界面

登录名:
密码:
success.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here

登录成功

4.编写实体类(持久化类):User.java

package com.domain;

import java.io.Serializable;

public class User implements Serializable{

	private String loginname;
	private String password;
	public User() {
		// TODO Auto-generated constructor stub
	}
	public String getLoginname() {
		return loginname;
	}
	public void setLoginname(String loginname) {
		this.loginname = loginname;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}
5.编写验证器:UserValidator.java

package com.validator;

import org.springframework.stereotype.Repository;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.domain.User;

/**
 * 实现Spring的Validator接口的用户验证器
 * @author ${HLoach}
 * 2017年4月6日
 */
@Repository("userValidator")//该注解将该对象注释为Spring容器中的一个Bean,名字为"userValidator"
public class UserValidator implements Validator{

	//该验证器能够对clazz类型的对象进行校验
	@Override
	public boolean supports(Class clazz) {
		//User指定的Class参数所表示的类或接口是否相同,或是否是其超类或超接口
		return User.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		/**
		 * 使用ValidationUtils中的一个静态方法rejectIfEmpty()来对loginname属性进行校验,
		 * 如果loginname属性是null或者空字符串的话,就拒绝验证通过。
		 */
		ValidationUtils.rejectIfEmpty(errors, "loginname", null, "登录名不能为空");
		ValidationUtils.rejectIfEmpty(errors, "password", null, "密码不能为空");
		User user = (User) target;
		if(user.getLoginname() != null && !user.getLoginname().equals("") && user.getLoginname().length() > 10){
			//使用Errors的rejectValue方法验证
			errors.rejectValue("loginname", null, "用户名不能超过10个字符");
		}
		if(user.getPassword() != null && !user.getPassword().equals("") && user.getPassword().length() < 6){
			errors.rejectValue("password", null, "密码不能小于6位");
			
		}
	}

}
6.编写处理器handler:UserController.java

package com.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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;

import com.domain.User;
import com.validator.UserValidator;

/**
 * 处理请求的handler
 * @author ${HLoach}
 * 2017年4月6日
 */
@Controller
public class UserController {

	@Autowired//自动装配
	@Qualifier("userValidator")
	private UserValidator userValidator;
	
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String login(
			@ModelAttribute User user,
			Model model,
			Errors errors
			){
		model.addAttribute("user", user);
		//调用userValidator的验证方法
		userValidator.validate(user, errors);
		//如果验证不通过,那么跳转回登录界面
		if(errors.hasErrors()){
			return "loginForm";
		}
		return "success";
	}
	
	@RequestMapping("/{formName}")
	public String show(@PathVariable String formName,Model model){
		User user = new User();
		model.addAttribute("user", user);
		return formName;
	}
}

7.配置SpringMVC的配置文件:springmvc.xml



	
	
	
	
	
	
	
	
		
		
		
			.jsp
		
	



二.JSR 303校验

JSR 303目前有两个实现,第一个实现是Hibernate Validator,可以从以下网站上下载:

https://sourceforge.net/projects/hibernate/files/hibernate-validator/

第二个是Apache bval,可以从以下网站下载:

http://bval.apache.org/downloads.html

Apache bval实现JSR 303和Hibernate Validator实现JSR 303基本一样,主要在于需要导入各自的包

例如:Apache bval实现JSR 303

1.在导入Spring的jar包的基础上,还需要导入Apache bval的jar包:


2.web.xml同第一点,SpringMVC的配置文件springmvc.xml如下:



	
	
	
	
	
	
	
	
		
		
		
			.jsp
		
	



3.编写实体类(持久化类):Users.java

package com.domain;

import java.io.Serializable;
import java.util.Date;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Pattern;

import org.apache.bval.constraints.Email;
import org.apache.bval.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;

public class Users implements Serializable{

	@NotEmpty(message="登录名不能为空")
	private String loginname;
	@NotEmpty(message="密码不能为空")
	private String password;
	@NotNull(message="年龄不能为空")
	@Min(value=18,message="年龄必须大于或者等于18岁")//Hibernate Validation可以使用@Range(min,max,message)验证属性值必须在合适的范围内
	private Integer age;
	@Email(message="必须是合法的邮箱地址")
	private String email;
	@DateTimeFormat(pattern="yyyy-MM-dd")//设定日期格式
	@Past(message="生日必须是一个过去的日期")
	private Date birthDay;
	@Pattern(regexp="[1][3,8][2,3,6,9][0-9]{8}",message="无效的电话号码")
	private String phone;
	public String getLoginname() {
		return loginname;
	}
	public void setLoginname(String loginname) {
		this.loginname = loginname;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public Date getBirthDay() {
		return birthDay;
	}
	public void setBirthDay(Date birthDay) {
		this.birthDay = birthDay;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	
}


4.编写视图:

registerForm.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>




测试JSR 303



	
登录名:
密码:
年龄:
邮箱:
生日(格式:2000-1-1):
电话:
success.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




测试JSR 303

测试JSR 303

登录名:${requestScopr.users.loginname } 密码:${requestScopr.users.password } 年龄:${requestScopr.users.age } 邮箱:${requestScopr.users.email } 生日:${requestScopr.users.birthDay } 电话:${requestScopr.users.phone }
5.编写处理器handler:UsersController.java

package com.controller;

import javax.validation.Valid;

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;

import com.domain.Users;




/**
 * 
 * @author ${HLoach}
 * 2017年4月7日
 */
@Controller
public class UsersController {

	@RequestMapping("/{formName}")
	public String show(@PathVariable String formName,Model model){
		Users users = new Users();
		model.addAttribute("users", users);
		return formName;
	}
	
	@RequestMapping(value="/register",method=RequestMethod.POST)
	public String register(
			@Valid @ModelAttribute Users users,
			Errors errors,
			Model model
			){
		//如果验证不通过,那么跳转回登录界面
		if(errors.hasErrors()){
			return "registerForm";
		}
		model.addAttribute("users", users);
		return "success";
	}
}

注意:Errors errors必须紧跟在@Valid @ModelAttribute Users users之后,否则会出现400错误。

测试结果如下:

SpringMVC的数据校验_第1张图片









你可能感兴趣的:(JavaEE)