Spring MVC 数据校验

数据校验是每个项目中必不可少的模块,Spring MVC 提供了两种数据校验的组件:

  • 基于 Validator 接口进行校验
  • 使用 Annotation JSR-303 标准校验

使用基于 Validator 接口进行校验会复杂一些,具体的数据校验的规则需要开发者手动设置。而使用 Annotation JSR-303 标准会相对简单一些,开发者不需要编写校验规则,直接通过注解的形式给每一条数据添加校验规则,具体操作是直接在实体类的属性上添加对应的校验注解即可。

一、基于 Validator 接口

1、创建实体类

import lombok.Data;

@Data
public class Person {
    private String name;
    private String password;
}

2、自定义数据校验器 PersonValidator,实现 Validator 接口,重写接口的抽象方法,加入校验规则。

public class PersonValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return Person.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmpty(errors,"name", null, "姓名不能为空");
        ValidationUtils.rejectIfEmpty(errors, "password", null, "密码不能为空");
    }
}

3、控制层业务方法

package com.southwind.controller;

import com.southwind.pojo.Person;
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("/validate")
public class PersonController {

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

    @PostMapping("/login")
    public String login(@Validated Person person, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return "login";
        }
        return "success";
    }
}

4、springmvc.xml 配置 Validator

<bean id="personValidator" class="com.southwind.validator.PersonValidator">bean>
<mvc:annotation-driven validator="personValidator">mvc:annotation-driven>

5、login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
<h1>用户登录h1>
<form:form modelAttribute="person" action="/validate/login" method="post">
    姓名:<form:input path="name">form:input><form:errors path="name">form:errors><br>
    密码:<form:input path="password">form:input><form:errors path="password">form:errors><br>
    <input type="submit" value="提交">
form:form>
body>
html>

success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
<h1>successh1>
body>
html>

6、页面效果
Spring MVC 数据校验_第1张图片
7、处理流程
Spring MVC 数据校验_第2张图片

二、Annotation JSR-303 标准

Hibernate Validator,通过注解完成校验规则的绑定。

  • @Null 只能为 null
  • @NotNull 不能为 null
  • @Size 设置数据长度
  • @NotEmpty 不能为空

1、pom.xml


    <dependency>
      <groupId>org.hibernategroupId>
      <artifactId>hibernate-validatorartifactId>
      <version>5.3.6.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.4.1.Finalversion>
    dependency>

2、创建实体类,通过注解的方式给属性指定校验规则

import lombok.Data;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;


import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

@Data
public class Account {
    @NotEmpty(message = "用户名不能为空")
    private String username;
    @Size(min = 6, max = 20,message = "密码长度为6-20位")
    private String password;
    @Email(regexp = "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\\\\\\\.[a-zA-Z0-9-]+)*\\\\\\\\.[a-zA-Z0-9]{2,6}$",message = "请输入正确的邮箱")
    private String email;
    @Pattern(regexp = "^1(3\\d|4[5-8]|5[0-35-9]|6[567]|7[01345-8]|8\\d|9[025-9])\\d{8}$", message ="请输入正确的电话格式")
    private String phone;

}

3、业务方法

import com.southwind.pojo.Account;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;

@Controller
@RequestMapping("/account")
public class RegisterController {

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

    @PostMapping("/register")
    public String register(@Valid Account account, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return "register";
        }
        return "success";
    }
}

4、springmvc.xml

 <mvc:annotation-driven>mvc:annotation-driven>

5、register.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
    <h1>用户注册h1>
    <form:form action="/account/register" modelAttribute="account" method="post">
        用户名:<form:input path="username">form:input><form:errors path="username">form:errors><br>
        密码:<form:input path="password">form:input><form:errors path="password">form:errors><br>
        邮箱:<form:input path="email">form:input><form:errors path="email">form:errors><br>
        电话:<form:input path="phone">form:input><form:errors path="phone">form:errors><br>
        <input type="submit" value="提交">
    form:form>
body>
html>

你可能感兴趣的:(SpringMVC,spring,mvc,java)