SpringMVC07_数据校验

SpringMVC07_数据校验


基于Validator接口的验证器

  • Account 实体类:
package com.blu.entity;
import lombok.Data;

@Data
public class Account {
    private String name;
    private String password;
}
  • AccountValidator
package com.blu.validator;

import com.blu.entity.Account;
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<?> clazz) {
        //判断是否是Account类型,如果是则返回true,表示支持验证。
        return Account.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        //若name为null,则在errors中添加“姓名不能为空”的错误信息,该信息会被验证器返回给前端。
        ValidationUtils.rejectIfEmpty(errors,"name",null,"姓名不能为空");
        ValidationUtils.rejectIfEmpty(errors,"password",null,"密码不能为空");
    }
    
}
  • login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
	<head>
    	<title>Titletitle>
	head>
	<body>
    	<form:form modelAttribute="account" action="/validator/login" method="post">
        	姓名:<form:input path="name"/><form:errors path="name"/><br>
        	密码:<form:input path="password"/><form:errors path="password"/><br>
        	<input type="submit" value="登录">
    	form:form>
    body>
html>
  • ValidatorHandler
package com.blu.controller;

import com.blu.entity.Account;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/validator")
public class ValidatorHandler {

    @GetMapping("/login")
    public String login(Model model){
        model.addAttribute("account",new Account());
        return "login";
    }

    @PostMapping("/login")
    public String login(@Validated Account account, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return "login";
        }else {
            return "index";
        }
    }
}
在请求参数上加 @Validated 注解表示开启验证
BindingResult 会获取校验错误信息
  • 在配置文件中注册验证器并使其生效:

<bean id="accountValidator" class="com.blu.validator.AccountValidator">bean>
<mvc:annotation-driven validator="accountValidator">mvc:annotation-driven>
  • 测试(输入http://localhost:8080/validator/login访问,因为是Get请求,故无数据校验)
    SpringMVC07_数据校验_第1张图片

  • 不填写数据直接点击登录,此时是Post请求,校验器开始起效:
    SpringMVC07_数据校验_第2张图片


基于Annotation JSR - 303 标准的验证
  • 需要导入支持这种标准的依赖,这里使用 Hibernate Validator
<dependency>
	<groupId>org.hibernategroupId>
	<artifactId>hibernate-validatorartifactId>
	<version>6.0.7.Finalversion>
dependency>
<dependency>
	<groupId>javax.validationgroupId>
	<artifactId>validation-apiartifactId>
	<version>2.0.1.Finalversion>
dependency>
<dependency>
	<groupId>org.jboss.logginggroupId>
	<artifactId>jboss-loggingartifactId>
	<version>3.3.2.Finalversion>
dependency>
  • 通过注解的方式直接在实体类中添加相关的验证规则
package com.blu.entity;

import lombok.Data;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

@Data
public class Person {
    @NotEmpty(message = "用户名不能为空")
    private String username;
    @Size(min = 6,max = 12, message = "密码的长度必须为6-12位")
    private String password;
    @Email(regexp = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$",message ="请输入正确的邮箱格式")
    private String email;
    @Pattern(regexp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$",message = "请输入正确的电话")
    private String phone;
}
  • 在配置文件中开启注解:
<mvc:annotation-driven>mvc:annotation-driven>
  • Handler
@GetMapping("/register")
public String register(Model model){
	model.addAttribute("person",new Person());
	return "registerpage";
}

@PostMapping("/register")
public String register(@Valid Person person, BindingResult bindingResult){
	if (bindingResult.hasErrors()){
		return "registerpage";
	}else {
		return "index";
	}
}
注意这里使用的注解不是 @Validated 而是 @Valid

校验规则详解: 
@Null 被注解的元素必须为null 
@NotNull 被注解的元素不能为null 
@Min(value) 被注解的元素必须是⼀个数字,其值必须⼤于等于指定的最⼩值 
@Max(value) 被注解的元素必须是⼀个数字,其值必须⼩于于等于指定的最⼤值 
@Email 被注解的元素必须是电⼦邮箱地址 
@Pattern 被注解的元素必须符合对应的正则表达式 
@Length 被注解的元素的⼤⼩必须在指定的范围内 
@NotEmpty 被注解的字符串的值必须⾮空 
Null 和 Empty 是不同的结果,String str = null,str 是 null,String str = "",str 不是 null,其值为空。

你可能感兴趣的:(SpringMVC)