码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC学习笔记七:SpringMVC的数据验证

时间:2017-03-26 01:17:30      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:eval   对象   学习   intern   长度   note   getc   traints   public   

SpringMVC支持JSR(Java Specification Requests, Java规范提案)303-Bean Validation数据验证规范,该规范的实现者很多,其中较常用的是

Hibernate Validator

需要加入的包pom.xml

    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.2.4.Final</version>
    </dependency>

hibernate-validator-5.2.4.Final.jar

validation-api-1.1.0.Final.jar

jboss-logging-3.2.1.Final.jar

 

对象实体类Student.java

package com.orange.model;

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

import org.hibernate.validator.constraints.NotEmpty;

import com.sun.istack.internal.NotNull;

public class Student {

    @NotEmpty(message="姓名不能为空")
    @Size(max=6, min=3, message="姓名长度必须大于{min},小于{max}")
    private String name;
    
    @NotNull
    @Max(value=100, message="小于100")
    @Min(value=1, message="小于1")
    private int age;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    
}

控制器StudentController.java

package com.orange.controller;

import java.util.List;

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

import com.orange.model.Student;

@Controller
@RequestMapping(value="/validator")
public class StudentController {

    @RequestMapping(value="/validator")
    public ModelAndView doTest(@Validated Student student, BindingResult br){
        
        ModelAndView mav = new ModelAndView();
        
        List<ObjectError> errors = br.getAllErrors();
        if(errors.size() > 0){
            FieldError nameError =  br.getFieldError("name");
            FieldError ageError = br.getFieldError("age");
            
            if(nameError != null){
                mav.addObject("nameError", nameError.getDefaultMessage());
            }
            if(ageError != null){
                mav.addObject("ageError", ageError.getDefaultMessage());
            }
            
            mav.setViewName("/index.jsp");
            
            return mav;
        }
        
        mav.addObject("student", student);
        
        mav.setViewName("/show.jsp");
        return mav;
    }
}

测试的jsp页面index.jsp

<%@ page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>    
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<base href="<%=basePath %>">
<title>Default Page</title>
</head>
<body>

<form action="validator/validator" method="post">
    name: <input type="text" name="name"><c:out value="${nameError }"></c:out><br>
    age: <input type="text" name="age"><c:out value="${ageError }"></c:out><br>
    <input type="submit" value="submit">
</form>
</body>
</html>

show.jsp

<%@ page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>    
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<base href="<%=basePath %>">
<title>Default Page</title>
</head>
<body>
<c:out value="${student.name }"></c:out><br>
<c:out value="${student.age }"></c:out>
</body>
</html>

spring-mvc.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/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd  
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    
    <!-- 扫描注解 -->
    <context:component-scan base-package="com.orange.controller" />    
    
    <!-- 注册验证器 -->
    <bean id="myValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
    </bean>
    
    <mvc:annotation-driven validator="myValidator"/>
</beans>

 

SpringMVC学习笔记七:SpringMVC的数据验证

标签:eval   对象   学习   intern   长度   note   getc   traints   public   

原文地址:http://www.cnblogs.com/djoker/p/6619026.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!