• spring mvc 使用jsr-303进行表单验证的方法介绍


    源代码来源:http://howtodoinjava.com/spring/spring-mvc/spring-bean-validation-example-with-jsr-303-annotations/,原文解释的更加清楚。此文主要是为了理顺整个项目的构建过程。

    采用JSR303来进行FORM验证,JSR-303实体验证的主要目的是通过注解对JAVA实体进行标准化验证。其主要目标是直接在java实体类中使用注解。即通过注释将需要验证的代码直接使用相应的验证规则进行验证,这样则不需要重新建立验证规则的类型。其中主要是使用了JSR-303标准。
    首先先看下项目的结构。
    首先,创建maven项目,然后修改其结构发布到tomcat服务器中。
    2.通过maven,引入需要的jar包,pom.xml文件如下:
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.howtodoinjava.mvc</groupId>
      <artifactId>jsr303Demo</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>war</packaging>
      
     <dependencies>
       <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.0.0.GA</version>
      </dependency>
      <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>4.3.1.Final</version>
      </dependency>
      <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
            </dependency>
     
            <!-- Spring MVC support -->
     
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>4.1.4.RELEASE</version>
            </dependency>
     
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>4.1.4.RELEASE</version>
            </dependency>
     
            <!-- Tag libs support for view layer -->
     
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
                <scope>runtime</scope>
            </dependency>
     
            <dependency>
                <groupId>taglibs</groupId>
                <artifactId>standard</artifactId>
                <version>1.1.2</version>
                <scope>runtime</scope>
            </dependency>
    </dependencies>
    </project>
    

      

     
    3. 在model中添加验证准则
    package com.howtodoinjava.demo.model;
    
    import java.io.Serializable;
    
    import javax.validation.constraints.Pattern;
    import javax.validation.constraints.Size;
    
    public class EmployeeVO implements Serializable 
    {
        private static final long serialVersionUID = 1L;
     
        private Integer id;
         
       
    @Size(min = 3, max = 20)
        private String firstName;
         
        @Size(min = 3, max = 20)
        private String lastName;
         
        @Pattern(regexp=".+@.+\.[a-z]+")
        private String email;
     
        //Setters and Getters
        public Integer getId() {
    return id;
    }
    
    public void setId(Integer id) {
    this.id = id;
    }
    
    public String getFirstName() {
    return firstName;
    }
    
    public void setFirstName(String firstName) {
    this.firstName = firstName;
    }
    
    public String getLastName() {
    return lastName;
    }
    
    public void setLastName(String lastName) {
    this.lastName = lastName;
    }
    
    public String getEmail() {
    return email;
    }
    
    public void setEmail(String email) {
    this.email = email;
    }
    
        @Override
        public String toString() {
            return "EmployeeVO [id=" + id + ", firstName=" + firstName
                    + ", lastName=" + lastName + ", email=" + email + "]";
        }
    }
    

      

     
    4.配置web.xml以及spring-servlet.xml文件(spring调度器)
    --- web.xml文件
    <web-app id="WebApp_ID" version="2.4"
        xmlns="http://java.sun.com/xml/ns/j2ee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
        http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
         
        <display-name>Spring Web MVC Hello World Application</display-name>
         
        <servlet>
            <servlet-name>spring</servlet-name>
                <servlet-class>
                    org.springframework.web.servlet.DispatcherServlet
                </servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
     
        <servlet-mapping>
            <servlet-name>spring</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
     
    </web-app>
    

      

     
    --- spring-servlet.xml文件
    <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"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">
     
        <context:component-scan base-package="com.howtodoinjava.demo" />
     
        <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
        <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
         
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/views/" />
            <property name="suffix" value=".jsp" />
        </bean>
         
        <bean  class="org.springframework.context.support.ResourceBundleMessageSource">
            <property name="basename" value="messages" />
        </bean>
         
    </beans>
    

      

    红色部分为通过配置文件配置解析器(disolver)。所以需要在WEB-INF文件下建立messages.properties文件,spring会自动去识别messages开头的文件。其内容如下:
    lbl.page=Add New Employee
    lbl.firstName=First Name
    lbl.lastName=Last Name
    lbl.email=Email Id
     
    5. 编写controller,创建EmployeeController.class,具体代码如下:
    package com.howtodoinjava.demo.controller;
     
    import java.util.Set;
     
    import javax.validation.ConstraintViolation;
    import javax.validation.Validation;
    import javax.validation.Validator;
    import javax.validation.ValidatorFactory;
     
    import org.springframework.beans.factory.annotation.Autowired;
    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.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.SessionAttributes;
    import org.springframework.web.bind.support.SessionStatus;
     
    import com.howtodoinjava.demo.model.EmployeeVO;
    import com.howtodoinjava.demo.service.EmployeeManager;
     
    @Controller
    @RequestMapping("/employee-module/addNew")
    @SessionAttributes("employee")
    public class EmployeeController {
        @Autowired
        EmployeeManager manager;
     
        private Validator validator;
     
        public EmployeeController()
        {
            ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
            validator = validatorFactory.getValidator();
        }
     
        @RequestMapping(method = RequestMethod.GET)
        public String setupForm(Model model) {
            EmployeeVO employeeVO = new EmployeeVO();
            model.addAttribute("employee", employeeVO);
            return "addEmployee";
        }
     
        @RequestMapping(method = RequestMethod.POST)
        public String submitForm(@ModelAttribute("employee") EmployeeVO employeeVO,
                BindingResult result, SessionStatus status) {
     
            Set<ConstraintViolation<EmployeeVO>> violations = validator.validate(employeeVO);
             
            for (ConstraintViolation<EmployeeVO> violation : violations)
            {
                String propertyPath = violation.getPropertyPath().toString();
                String message = violation.getMessage();
                // Add JSR-303 errors to BindingResult
                // This allows Spring to display them in view via a FieldError
                result.addError(new FieldError("employee",propertyPath,
     
                                       "Invalid "+ propertyPath + "(" + message + ")"));
            }
     
            if (result.hasErrors()) {
                return "addEmployee";
            }
            // Store the employee information in database
            // manager.createNewRecord(employeeVO);
     
            // Mark Session Complete
            status.setComplete();
            return "redirect:addNew/success";
        }
     
        @RequestMapping(value = "/success", method = RequestMethod.GET)
        public String success(Model model) {
            return "addSuccess";
        }
    }
    

      

     
    5.创建view,一个addEmployee.jsp和一个addSuccess.jsp,分别如下:
    --- addEmployee.jsp文件
    <%@ page contentType="text/html;charset=UTF-8"%>
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
    <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
     
    <html>
    <head>
        <title>Add Employee Form</title>
    </head>
     
    <body>
        <h2><spring:message code="lbl.page" text="Add New Employee" /></h2>
        <br/>
        <form:form method="post" modelAttribute="employee">
            <table>
                <tr>
                    <td><spring:message code="lbl.firstName" text="First Name" /></td>
                    <td><form:input path="firstName" /></td>
                    <td><form:errors path="firstName" cssClass="error" /></td>
                </tr>
                <tr>
                    <td><spring:message code="lbl.lastName" text="Last Name" /></td>
                    <td><form:input path="lastName" /></td>
                    <td><form:errors path="lastName" cssClass="error" /></td>
                </tr>
                <tr>
                    <td><spring:message code="lbl.email" text="Email Id" /></td>
                    <td><form:input path="email" /></td>
                    <td><form:errors path="email" cssClass="error" /></td>
                </tr>
                <tr>
                    <td colspan="3"><input type="submit" value="Add Employee"/></td>
                </tr>
            </table>
        </form:form>
    </body>
    </html>
     
    

      

    --- addSuccess.jsp文件
    <html>
        <head>
            <title>Add Employee Success</title>
        </head>
        <body>
            Employee has been added successfully.
        </body>
    </html>
    

      

     
    到此使用JSR-303验证表单数据的例子就结束了。通过url = http://localhost:8080/jsr303Demo/employee-module/addNew进行访问,则
    点击Add Employee按钮,当输入数据不符合验证规则时,则会显示错误信息。
  • 相关阅读:
    onchange 事件
    JavaScript 声明全局变量和局部变量
    Window 对象 HTML框架标签(Frame)
    HTML DOM Document 对象
    JavaScript 对象
    HTML <frame> 标签的 src 属性
    HTML DOM open() 方法
    数据类型
    python
    angular 在formGroup中失效报错 ngModel cannot be used to register form controls with a parent formGroup directive
  • 原文地址:https://www.cnblogs.com/Eunice-mogu/p/5227770.html
Copyright © 2020-2023  润新知