Spring MVC - Hibernate Validator 示例



以下示例展示瞭如何在使用 Spring Web MVC 框架的表單中使用錯誤處理和驗證器。首先,讓我們準備好一個可用的 Eclipse IDE,並按照以下步驟使用 Spring Web 框架開發一個基於動態表單的 Web 應用程式。

步驟 描述
1 在 Spring MVC - Hello World 章節中說明的 com.tutorialspoint 包下建立一個名為 TestWeb 的專案。
2 在 com.tutorialspoint 包下建立 Java 類 Student、StudentController 和 StudentValidator。
3 在 jsp 子資料夾下建立檢視檔案 addStudent.jsp 和 result.jsp。
4 下載 Hibernate Validator 庫 Hibernate Validator。解壓縮 hibernate-validator-5.3.4.Final.jar 和下載的 zip 檔案的 required 資料夾下的必需依賴項。將它們放入您的 CLASSPATH 中。
5 在 SRC 資料夾下建立一個屬性檔案 messages.properties。
6 最後一步是建立原始檔和配置檔案的內容,並匯出應用程式,如下所述。

Student.java

package com.tutorialspoint;

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.tutorialspoint;

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";
   }
}

messages.properties

NotEmpty.student.name = Name is required!
Range.student.age = Age value must be between 1 and 150!

這裡,鍵是 <Annotation>.<object-name>.<attribute>。值是要顯示的訊息。

TestWeb-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.tutorialspoint" />
   <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 物件中傳遞了一個空的 Studentobject>,名稱為“command”,因為如果在 JSP 檔案中使用 <form:form> 標籤,Spring 框架會期望一個名為“command”的物件。因此,當呼叫 student() 方法時,它會返回 addStudent.jsp 檢視。

第二個服務方法 addStudent() 將針對 HelloWeb/addStudent URL 上的 POST 方法呼叫。您將根據提交的資訊準備模型物件。最後,將從服務方法返回“result”檢視,這將導致渲染 result.jsp。如果使用驗證器生成了錯誤,則返回相同的檢視“addStudent”,Spring 會自動將 BindingResult 中的錯誤訊息注入檢視。

addStudent.jsp

<%@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>Student Information</h2>
      <form:form method = "POST" action = "/TestWeb/addStudent" commandName = "student">
      <form:errors path = "*" cssClass = "errorblock" element = "div" />
         <table>
            <tr>
               <td><form:label path = "name">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">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">id</form:label></td>
               <td><form:input path = "id" /></td>
               </tr>
            <tr>
               <td colspan = "2">
               <input type = "submit" value = "Submit"/>
               </td>
            </tr>
         </table>  
      </form:form>
   </body>
</html>

這裡,我們使用 <form:errors /> 標籤,路徑為“*”,來渲染錯誤訊息。例如 -

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

它將渲染所有輸入驗證的錯誤訊息。我們使用 <form:errors /> 標籤,路徑為“name”,來渲染名稱欄位的錯誤訊息。

例如 -

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

它將渲染名稱和年齡欄位驗證的錯誤訊息。

result.jsp

<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
   <head>
      <title>Spring MVC Form Handling</title>
   </head>
   <body>

      <h2>Submitted Student Information</h2>
      <table>
         <tr>
            <td>Name</td>
            <td>${name}</td>
         </tr>
         <tr>
            <td>Age</td>
            <td>${age}</td>
         </tr>
         <tr>
            <td>ID</td>
            <td>${id}</td>
         </tr>
      </table>  
   </body>
</html>

完成原始檔和配置檔案的建立後,匯出您的應用程式。右鍵單擊您的應用程式,使用 匯出 → WAR 檔案 選項並將 HelloWeb.war 檔案儲存在 Tomcat 的 webapps 資料夾中。

現在,啟動 Tomcat 伺服器,並確保您可以使用標準瀏覽器從 webapps 資料夾訪問其他網頁。嘗試 URL - https://:8080/TestWeb/addStudent,如果輸入了無效值,我們將看到以下螢幕。

Spring Validation Result
廣告

© . All rights reserved.