javascript
Spring MVC Hibernate验证器使用示例
下面的示例演示如何使用Spring Web MVC框架在表單中使用錯(cuò)誤處理和驗(yàn)證器。 首先使用Eclipse IDE,并按照以下步驟使用Spring Web Framework開(kāi)發(fā)基于動(dòng)態(tài)表單的Web應(yīng)用程序:
完整的項(xiàng)目文件目錄結(jié)構(gòu)如下所示 -
Student.java 的代碼如下所示 -
package com.yiibai.springmvc; import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.Range;public class Student {@Range(min = 1, max = 150) private Integer age;@NotEmptyprivate 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.yiibai.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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"><context:component-scan base-package="com.yiibai.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>這里的第一個(gè)服務(wù)方法student(),已經(jīng)在ModelAndView對(duì)象中傳遞了一個(gè)名稱(chēng)為“command”的空對(duì)象,因?yàn)槿绻贘SP文件中使用<form:form>標(biāo)簽,spring框架需要一個(gè)名稱(chēng)為“command”的對(duì)象。 所以當(dāng)調(diào)用student()方法時(shí),返回addStudent.jsp視圖。
第二個(gè)服務(wù)方法addStudent()將在URL: HibernateValidator/addStudent 上的POST方法被調(diào)用。將根據(jù)提交的信息準(zhǔn)備模型對(duì)象。 最后從服務(wù)方法返回“result”視圖,這將渲染result.jsp。 如果使用validator生成錯(cuò)誤,則返回相同的視圖“addStudent”,則Spring自動(dòng)從視圖中的BindingResult注入錯(cuò)誤消息并顯示出來(lái)。
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>學(xué)生信息</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">編號(hào):</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 />標(biāo)記,其中path =“*”來(lái)呈現(xiàn)錯(cuò)誤消息。例如-
<form:errors path="*" cssClass="errorblock" element="div" />它將呈現(xiàn)所有輸入驗(yàn)證的錯(cuò)誤消息。
使用帶有path =“name”的<form:errors />標(biāo)記來(lái)渲染name字段的錯(cuò)誤消息。例如 -
它將呈現(xiàn)姓名(name)和年齡(age)字段驗(yàn)證的錯(cuò)誤消息。
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>提交的學(xué)生信息如下 -</h2><table><tr><td>姓名:</td><td>${name}</td></tr><tr><td>年齡:</td><td>${age}</td></tr><tr><td>編號(hào):</td><td>${id}</td></tr> </table> </body> </html>完成創(chuàng)建源和配置文件后,發(fā)布應(yīng)用程序到Tomcat服務(wù)器。
現(xiàn)在啟動(dòng)Tomcat服務(wù)器,當(dāng)訪(fǎng)問(wèn)URL => http://localhost:8080/HibernateValidator/addStudent , 如果Spring Web應(yīng)用程序沒(méi)有問(wèn)題,應(yīng)該看到以下結(jié)果:
原文出自【易百教程】,商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)保留原文鏈接:https://www.yiibai.com/spring_mvc/springmvc_hibernate_validator.html
與50位技術(shù)專(zhuān)家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的Spring MVC Hibernate验证器使用示例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【软考】 2019年上半年软件设计师考试
- 下一篇: Spring MVC生成PDF文件代码示