Github代码地址

SpringMVC10数据验证

在之前的案例上面! 引入需要的验证jar包

 

创建index.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML>
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
      <form action="student/addStudent"  method="post">
     年龄:<input type="text" name="age"/> ${ageE} <br/>
     姓名:  <input type="text" name="userName"/>${userNameE}<br/>
   电话:<input type="text" name="phone"> ${phoneE}<br/> 
       <input type="submit" value="新增"/>
      </form>
  </body>
</html>

 

对应的Student类

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotBlank;

/**
 * 
 * @NotNull   作用在基本数据类型上
 * @NotBlank  作用在String上
 * @NotEmpty  作用在集合上
 *  @Min  最小值
 *  @Max  最大值
 *  @Size  字符串的长度
 * @Pattern  自定义验证规则 
 * 
 */
public class Student {

      @NotNull(message="年龄不能为空")
      @Min(value=0,message="年龄不能低于{value}")
      @Max(value=150,message="年龄不能高于{value}")
      private  Integer  age; //年龄
      @NotBlank(message="姓名不能为空")
      @Size(min=6,max=10,message="长度必须在{min}---{max}之间")
      private  String  userName;  //姓名
      @NotBlank(message="手机号不能为空")
      @Pattern(regexp="^1[345789]\\d{9}$",message="手机格式不正确")
      private  String  phone;  //电话
      
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public Student(Integer age, String userName, String phone) {
        super();
        this.age = age;
        this.userName = userName;
        this.phone = phone;
    }
    public Student() {
        super();
    }
       
    

}

 

对应的controller

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import sun.util.calendar.BaseCalendar;

import cn.bdqn.bean.Student;

@Controller
@RequestMapping("/student")
public class StudentController  {
    
    /**
     * 
     *@Validated  :会对student对象中所有标注 注解的属性进行验证!
     *BindingResult:如果 验证出现错误 ,就会把错误信息给这个result
     *
     *result.getFieldError("age").getDefaultMessage()
     *获取我们设置的错误 信息!
     *
     */
    @RequestMapping("/addStudent")
    public ModelAndView  addStudent(@Validated Student student,BindingResult result) {
        System.out.println("进入了  addStudent");
        ModelAndView mv=new ModelAndView();
        if (result.hasErrors()) {  //出现了验证错误
            if (result.getFieldError("age")!=null) {  //证明age验证有错误
                mv.addObject("ageE", result.getFieldError("age").getDefaultMessage());
            }
            if (result.getFieldError("userName")!=null) {  //证明userName验证有错误
                mv.addObject("userNameE", result.getFieldError("userName").getDefaultMessage());
            }
            if (result.getFieldError("phone")!=null) {  //证明phone验证有错误
                mv.addObject("phoneE", result.getFieldError("phone").getDefaultMessage());
            }
            mv.setViewName("/index.jsp");
            return   mv;
        }
        mv.setViewName("/success.jsp");
       return   mv;
    }
    
    
    
    
}

 

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:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    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/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        ">
  <!-- 配置springmvc的组件  -->
  <context:component-scan base-package="cn.bdqn.controller"/>
  <!-- 开启 注解的方式-->
  <mvc:annotation-driven validator="myValidator"/>
  <!-- 生成我们的验证器 -->
  <bean  id="myValidator"  class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
  </bean>
  
</beans>

 

posted @ 2016-12-12 11:00  @小葱拌豆腐  阅读(359)  评论(0编辑  收藏  举报

霸气