SpringMVC学习(7):数据校验

前言

数据的校验是交互网站一个必不可缺的的功能,前端的js校验可以涵盖大部分的校验职责,但是有的用户会绕过浏览器使用http请求工具直接向后端请求一些违法数据,为了防止这种脏数据落到数据库中的情况,服务端的数据校验也是必要的。

自定义数据校验

基于Validator接口的方式需要自定义Validator验证器,每一条数据的验证规则需要自己手动完成。

1、创建实体类Admin

package com.jex.entity;

public class Admin {
    private String name;
    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

2、自定义校验器AdminValidator,实现Validator接口

package com.jex.validator;


import com.jex.entity.Admin;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;


public class AdminValidator implements Validator {

    public boolean supports(Class<?> clazz) {
        // TODO Auto-generated method stub
        return Admin.class.equals(clazz);
    }

    public void validate(Object target, Errors errors) {
        // TODO Auto-generated method stub
        ValidationUtils.rejectIfEmpty(errors, "name", null, "账号不能为空");
        ValidationUtils.rejectIfEmpty(errors, "password", null, "密码不能为空");
    }

}

3、springmvc.xml中配置adminValidator

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 配置自动扫描 -->
    <context:component-scan base-package="com.jex.controller"></context:component-scan>

    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/"></property>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 基于Validator的配置 -->
    <mvc:annotation-driven validator="adminValidator"/>

    <bean id="adminValidator" class="com.jex.validator.AdminValidator"/>

</beans>

4、编写业务方法

@Controller
public class ValidController {

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(Model model){
        Admin admin = new Admin();
        model.addAttribute(admin);
        return "login";
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String loginPost(@Validated Admin admin, BindingResult result){
        if (result.hasErrors()){
            return "login";
        }
        return "success";
    }

}

注意:参数Admin前需要加上@Validated注解,表明需要spring对其进行校验,而校验的信息会存放到其后的BindingResult中。注意,必须相邻,中间不能有其他参数,如果有多个参数需要校验,形式可以如下。loginPost(@Validated Admin admin, BindingResult adminResult ,@Validated User user, BindingResult userResult),即一个校验类对应一个校验结果。

5、创建 login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
<h1>管理员登录</h1>
<form:form modelAttribute="admin" action="login" method="post">
    账号:<form:input path="name" /><form:errors path="name"/><br/>
    密码:<form:password path="password" /><form:errors path="password"/><br/>
    <input type="submit" value="提交"/>
</form:form>
</body>
</html>

6、运行

 

Annotation JSR303

Annotation JSR303是一项标准,规定一些校验规范即校验注解,如@Null,@NotNull,@Pattern,他们位于javax.validation.constraints包下,只提供规范不提供实现。使用Annotation JSR-303标准进行验证,需要导入支持这种标准的jar包,这里我们使用Hibernate Validator。

校验规则解释:

规则说明
@Null限制必须不为null
@NotNull限制必须不为null
@NotEmpty验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)
@NotBlank验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用
@AssertFalse限制必须为false
@AssertTrue限制必须为true
@Pattern(value)限制必须符合指定的正则表达式
@DecimalMax(value)限制必须为一个不大于指定值的数字
@DecimalMin(value)限制必须为一个不小于指定值的数字
@Digits(integer,fraction)限制必须为一个小数,且整数部分的位数不能超过integer,小数部分的位数不能超过fraction
@Past验证注解的元素值(日期类型)比当前时间早
@Future验证注解的元素值(日期类型)比当前时间晚
@Max(value)限制必须为一个不大于指定值的数字
@Min(value)限制必须为一个不小于指定值的数字
@Size(max,min)限制字符长度必须在min到max之间
@Email验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式

1、在pom.xml添加Hibernate Validator依赖

 <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>5.1.3.Final</version>
    </dependency>

    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
      <version>1.1.0.Final</version>
    </dependency>

2、配置springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 配置自动扫描 -->
    <context:component-scan base-package="com.jex.controller"></context:component-scan>

    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/"></property>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- JSR-303配置 -->
    <mvc:annotation-driven />

</beans>

3、创建User实体类

package com.jex.entity;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

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

public class User {
    @NotEmpty(message = "用户名不能为空")
    private String username;
    @Size(min = 8,max = 20,message = "密码长度为8-12位")
    private String password;

    @Pattern(regexp = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\\\d{8}$",message="请输入正确的电话格式")
    private String phone;

    @Email(regexp = "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$", message = "请输入正确的邮箱格式")
    private String email;
    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;
    }

    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }

}

注意:每一个注解都包含了message字段,用于校验失败时作为提示信息。特殊的校验注解,如Pattern(正则校验),是可以自己添加正则表达式。

4、编写业务方法

@Controller
public class ValidController {

    @RequestMapping(value = "/register",method = RequestMethod.GET)
    public String register(Model model){
        User user = new User();
        model.addAttribute(user);
        return "register";
    }

    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public String registerPost(@Validated User user,BindingResult result){
        if (result.hasErrors()){
            return "register";
        }
        return "success";
    }

}

5、创建register.jsp

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

6、运行

 

源码

链接:
https://pan.baidu.com/s/1J0qviVFc55sBM2C8WE1N_g 
提取码:eqc5

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值