SSM-SpringMVC-31:SpringMVC中利用hibernate-validator做后台校验

 

 

 

------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥-------------

 

 

校验有三种:前台页面校验(例如js和h5),后台校验,数据库校验

但是一般能不用数据库校验就不用数据库校验,因为性能损耗严重,

所以,我们用前台和后台俩种,可以说最好,绝大部分情况下,前台后台都要写,如果一个用户比较搞事,直接把它浏览器上的js给禁用掉了,那么如果没有后台校验,他将直接杀向数据库

 

很多人一提hibernate就说,哦,是一个框架,ORM框架,数据库访问层的框架,SSH的那个H!!!!

这个答案其实很一般,HibernateORM是Hibernate框架其中的一个重要的组成部分之一,像其它的例如hibernate-validator这个校验框架其实很不错

 

好了,不扯皮了,说说怎么用。。。。。。。

 

案例:

  一,引入jar包

 

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

        <!--validation api-->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>

 

      也不知道大家看到了没有,由于是maven项目,只需要俩个节点就好,它会自动引入相关联的jar,如果不是maven,或者maven不好用,则还需要再引俩个jar,我把全部jar包的节点放上来

 

   <!--数据验证-->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>4.0.1.GA</version>
    </dependency>

    <!--jboss logging-->
    <dependency>
      <groupId>org.jboss.logging</groupId>
      <artifactId>jboss-logging</artifactId>
      <version>3.3.0.Final</version>
    </dependency>

    <!--validation api-->
    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
      <version>1.0.0.GA</version>
    </dependency>

    <!--slf4j api-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.21</version>
    </dependency>
数据校验全部的jar,合起来

 

  二,自己的大配置文件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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd">

    <!--包扫描器-->
    <context:component-scan base-package="cn.dawn.day23validator"></context:component-scan>
    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/day23/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    
    <!--验证器-->
    <bean id="myvalidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <!--注入hibernate的验证器-->
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
    </bean>

    <!--绑定注解驱动-->
    <mvc:annotation-driven validator="myvalidator"></mvc:annotation-driven>

</beans>

 

  三,修改web.xml中央调度器的上下文配置位置为上面那个配置文件

  四,建一个实体类:里面用注解做校验,很好理解,有些用正则

 

package cn.dawn.day23validator;

import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;


import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.util.Date;

/**
 * Created by Dawn on 2018/3/31.
 */
public class UserInfo {
    @NotEmpty(message = "用户名不能为空")
    @Size(min = 6,max = 20,message = "用户名的长度必须在{min}-{max}之间")
    private String username;

    @Max(value = 150,message = "最老150岁")
    @Min(value = 0,message = "最小0岁")
    private Integer userage;

    @NotEmpty(message = "手机号码不能为空")
    @Pattern(regexp = "^1[3|5|7|8|9]\\d{9}$",message = "手机号码格式不正确")
    private String userphone;
    @NotEmpty(message = "邮箱不能为空")
    @Pattern(regexp = "^\\w+@\\w+\\.\\w+$",message = "邮箱格式不正确")
    private String email;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getUserage() {
        return userage;
    }

    public void setUserage(Integer userage) {
        this.userage = userage;
    }

    public String getUserphone() {
        return userphone;
    }

    public void setUserphone(String userphone) {
        this.userphone = userphone;
    }

    public String getEmail() {
        return email;
    }

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

 

  五,自定义的处理器和处理方法

 

package cn.dawn.day23validator;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;

/**
 * Created by Dawn on 2018/3/31.
 */
@Controller
public class ValidatorController {
    @RequestMapping("/validatorZC")
    public String validatorZC(@Valid UserInfo userInfo, BindingResult br, Model model){
        //判定br中错误数是否大于0,如果true,证明有一个验证失败了
        if (br.getErrorCount()>0){
            FieldError userage=br.getFieldError("userage");
            FieldError username=br.getFieldError("username");
            FieldError userphone=br.getFieldError("userphone");
            FieldError email=br.getFieldError("email");

            //哪个验证失败,就回显示哪个
            if(userage!=null){
                String useragemsg = userage.getDefaultMessage();
                model.addAttribute("useragemsg",useragemsg);
            }
            if(username!=null){
                String usernamemsg = username.getDefaultMessage();
                model.addAttribute("usernamemsg",usernamemsg);
            }
            if(userphone!=null){
                String userphonemsg = userphone.getDefaultMessage();
                model.addAttribute("userphonemsg",userphonemsg);
            }
            if(email!=null){
                String emailmsg = email.getDefaultMessage();
                model.addAttribute("emailmsg",emailmsg);
            }

            //这个if里面就是肯定有错误,回显示名字
            model.addAttribute("username",userInfo.getUsername());
            /*返回注册页面*/
            return "validator";
        }
        /*注册成功*/
        return "success";

    }
}

 

  六,jsp页面

    6.1validator.jsp页面

 

<%--
  Created by IntelliJ IDEA.
  User: Dawn
  Date: 2018/3/31
  Time: 17:21
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>数据校验</h1>
<form action="${pageContext.request.contextPath}/validatorZC" method="post">
    年龄:<input name="userage" /> <span>${useragemsg }</span><br/><br/>
    姓名:<input name="username" value="${username}"/><span>${usernamemsg }</span><br/><br/>
    电话:<input name="userphone"/><span>${userphonemsg }</span><br/><br/>
    邮箱:<input name="email"/> <span>${emailmsg}</span><br/><br/>
    <input type="submit" value="注册"/>
</form>
</body>
</html>

 

    6.2success.jsp页面

 

<%@ page language="java" pageEncoding="utf-8" isELIgnored="false" %>
<html>
<body>
<%--<img src="image/1.jpg">--%>
<h2>Success!</h2>
</body>
</html>

 

  七,启动tomcat,访问validator.jsp页面

 

 

有什么不懂的,联系我,原作者:晨曦Dawn

转载请注明出处    http://www.cnblogs.com/DawnCHENXI/p/8684167.html

 

posted @ 2018-03-31 21:02  晨曦Dawn  阅读(401)  评论(0编辑  收藏  举报