SpringMVC 专题
您的位置:java > SpringMVC专题 > Spring MVC Hibernate验证器
Spring MVC Hibernate验证器
作者:--    发布时间:2019-11-19

下面的示例演示如何使用spring web mvc框架在表单中使用错误处理和验证器。 首先使用eclipse ide,并按照以下步骤使用spring web framework开发基于动态表单的web应用程序:

  1. 创建一个名称为 hibernatevalidator 的动态web项目。
  2. com.h3.springmvc 包下创建三个java类:studentstudentcontroller
  3. jsp子文件夹下创建两个视图文件:addstudent.jsp, result.jsp
  4. 下载hibernate validator库 - hibernate validator。解压缩hibernate-validator-5.3.4.final.jar和所需的依赖关系存并将它们放在classpath中。
  5. src文件夹下创建属性文件messages.properties
  6. 最后一步是创建所有源和配置文件的内容并运行应用程序,详细如下所述。

完整的项目文件目录结构如下所示 -

student.java 的代码如下所示 -

package com.h3.springmvc;
import org.hibernate.validator.constraints.notempty;
import org.hibernate.validator.constraints.range;

public class student {

   @range(min = 1, max = 150) 
   private integer age;
   @notempty
   private string name;
   private integer id;

   public void setage(integer age) {
      this.age = age;
   }
   public integer getage() {
      return age;
   }

   public void setname(string name) {
      this.name = name;
   }
   public string getname() {
      return name;
   }

   public void setid(integer id) {
      this.id = id;
   }
   public integer getid() {
      return id;
   }
}

studentcontroller.java 的代码如下所示 -

package com.h3.springmvc;
import org.springframework.stereotype.controller;
import org.springframework.ui.model;
import org.springframework.validation.bindingresult;
import org.springframework.validation.annotation.validated;
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.servlet.modelandview;

@controller
public class studentcontroller {

   @requestmapping(value = "/addstudent", method = requestmethod.get)
   public modelandview student() {
      return new modelandview("addstudent", "command", new student());
   }

   @modelattribute("student")
   public student createstudentmodel() {    
      return new student();
   }

   @requestmapping(value = "/addstudent", method = requestmethod.post)
   public string addstudent(@modelattribute("student") @validated student student, 
      bindingresult bindingresult, model model) {
      if (bindingresult.haserrors()) {
         return "addstudent";
      }
      model.addattribute("name", student.getname());
      model.addattribute("age", student.getage());
      model.addattribute("id", student.getid());

      return "result";
   }
}

message.properties 配置如下所示 -

notempty.student.name = name is required!
range.student.age = age value must be between 1 and 150!

这里的键可以是<annotation>.<object-name>.<attribute>value是要显示的消息。

hibernatevalidator-servlet.xml 配置如下所示 -

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
   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
   http://www.springframework.org/schema/mvc
   http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

   <context:component-scan base-package="com.h3.springmvc" />
   <mvc:annotation-driven />
   <bean class="org.springframework.context.support.resourcebundlemessagesource"
      id="messagesource">
      <property name="basename" value="messages" />
   </bean>
   <bean class="org.springframework.web.servlet.view.internalresourceviewresolver">
      <property name="prefix" value="/web-inf/jsp/" />
      <property name="suffix" value=".jsp" />      
   </bean>
</beans>

这里的第一个服务方法student(),已经在modelandview对象中传递了一个名称为“command”的空对象,因为如果在jsp文件中使用<form:form>标签,spring框架需要一个名称为“command”的对象。 所以当调用student()方法时,返回addstudent.jsp视图。

第二个服务方法addstudent()将在url: hibernatevalidator/addstudent 上的post方法被调用。将根据提交的信息准备模型对象。 最后从服务方法返回“result”视图,这将渲染result.jsp。 如果使用validator生成错误,则返回相同的视图“addstudent”,则spring自动从视图中的bindingresult注入错误消息并显示出来。

addstudent.jsp 的代码如下所示 -

<%@ page contenttype="text/html; charset=utf-8" %>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>spring mvc form handling</title>
</head>
<style>
.error {
   color: #ff0000;
}

.errorblock {
   color: #000;
   background-color: #ffeeee;
   border: 3px solid #ff0000;
   padding: 8px;
   margin: 16px;
}
</style>
<body>

<h2>学生信息</h2>
<form:form method="post" action="/hibernatevalidator/addstudent" commandname="student">
   <form:errors path="*" cssclass="errorblock" element="div" />
   <table>
    <tr>
        <td><form:label path="name">姓名:</form:label></td>
        <td><form:input path="name" /></td>
        <td><form:errors path="name" cssclass="error" /></td>
    </tr>
    <tr>
        <td><form:label path="age">年龄:</form:label></td>
        <td><form:input path="age" /></td>
        <td><form:errors path="age" cssclass="error" /></td>
    </tr>
    <tr>
        <td><form:label path="id">编号:</form:label></td>
        <td><form:input path="id" /></td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="submit" value="提交"/>
        </td>
    </tr>
</table>  
</form:form>
</body>
</html>

上面的代码中使用了<form:errors />标记,其中path =“*”来呈现错误消息。例如-

<form:errors path="*" cssclass="errorblock" element="div" />

它将呈现所有输入验证的错误消息。
使用带有path =“name”<form:errors />标记来渲染name字段的错误消息。例如 -

<form:errors path="name" cssclass="error" />
<form:errors path="age" cssclass="error" />

它将呈现姓名(name)和年龄(age)字段验证的错误消息。

result.jsp 的代码如下所示 -

<%@ page contenttype="text/html; charset=utf-8" %>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>spring mvc form handling</title>
</head>
<body>

<h2>提交的学生信息如下 -</h2>
   <table>
    <tr>
        <td>姓名:</td>
        <td>${name}</td>
    </tr>
    <tr>
        <td>年龄:</td>
        <td>${age}</td>
    </tr>
    <tr>
        <td>编号:</td>
        <td>${id}</td>
    </tr>
</table>  
</body>
</html>

完成创建源和配置文件后,发布应用程序到tomcat服务器。

现在启动tomcat服务器,当访问url => http://localhost:8080/hibernatevalidator/addstudent , 如果spring web应用程序没有问题,应该看到以下结果:


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册