<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # Spring MVC 示例 – 顯示,驗證和提交表單 > 原文: [https://howtodoinjava.com/spring-mvc/spring-mvc-display-validate-and-submit-form-example/](https://howtodoinjava.com/spring-mvc/spring-mvc-display-validate-and-submit-form-example/) 在任何 **spring web mvc 應用程序**中,我們經常必須處理表單。 應用程序首先顯示一個表單,然后用戶填寫該表單并將其提交給服務器。 在服務器上,應用程序需要捕獲表單輸入并處理輸入(例如,存儲在數據庫中)并返回成功視圖。 在此 **spring mvc 示例**中,我們將學習顯示表單,然后學習處理提交的表單字段。 在此示例中,我們將創建具有添加員工功能的員工管理模塊。 它具有以下功能: 1. 在初始頁面加載時顯示空白表格 2. 如果提交的表單具有空字段,則顯示錯誤消息 3. 成功提交表單后,重定向到另一個屏幕,顯示成功消息 ![Spring MVC Form Example - Blank Form](https://img.kancloud.cn/43/2c/432ce8a84fdf5451769974fd3818d242_474x263.jpg) Spring MVC Form Example – 空白表單 [下載源碼](https://drive.google.com/file/d/0B7yo2HclmjI4bmVXdkhiVTJVejQ/view?usp=sharing) ```java 目錄 1. 創建模型數據 2. 創建表單視圖 3. 創建表單控制器 4. 表單驗證 5. 演示 ``` 讓我們開始一個接一個地添加應用程序組件,然后記下重要的事情。 ## 1\. Spring MVC 模型數據 對于此示例應用程序,`EmployeeVO`類用作模型。 它將保存數據,視圖將使用這些數據來呈現并發布回控制器。 `EmployeeVO.java` ```java package com.howtodoinjava.demo.model; import java.io.Serializable; public class EmployeeVO implements Serializable { private static final long serialVersionUID = 1L; private Integer id; private String firstName; private String lastName; private String email; //Getters and Setters @Override public String toString() { return "EmployeeVO [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]"; } } ``` ## 2\. Spring MVC 表單視圖 該應用程序使用兩個視圖,即一個用于顯示表單,另一個用于顯示成功消息。 #### 2.1. 輸入表單視圖 `addEmployee.jsp` ```java <%@ 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> </tr> <tr> <td><spring:message code="lbl.lastName" text="Last Name" /></td> <td><form:input path="lastName" /></td> </tr> <tr> <td><spring:message code="lbl.email" text="Email Id" /></td> <td><form:input path="email" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="Add Employee"/></td> </tr> </table> </form:form> </body> </html> ``` **要點:** 1. Spring `<form:form>`標簽聲明了兩個屬性。 用于指示表單的`method="post"`屬性在提交時執行 HTTP POST 請求。 并且用于表示表單數據的`modelAttribute="employee`屬性被綁定到名為**員工**的模型。 2. 表單的各種`<form:input>`標簽使用屬性路徑來指示它們綁定到的表單字段。 它們向用戶顯示該字段的原始值,該值要么是綁定的屬性值,要么是由于綁定錯誤而被拒絕的值。 它們必須在`<form:form>`標簽內使用,該標簽定義了一種通過其名稱綁定到`modelAttribute`的格式。 3. 最后,您可以找到標準的 HTML 標記`<input type="submit" />`,該標記會生成一個“提交”按鈕,并觸發向服務器發送數據,然后是關閉表單的標記。 請注意,`<spring:message>`標簽用于顯示類路徑中存在的[**消息資源文件**](https://howtodoinjava.com/spring/spring-mvc/spring-mvc-resourcebundleviewresolver-configuration-example/)的字段標簽。 在我們的例子中,消息資源的內容如下: `messages.properties` ```java lbl.page=Add New Employee lbl.firstName=First Name lbl.lastName=Last Name lbl.email=Email Id ``` #### 2.2. 成功頁面視圖 `addSuccess.jsp` ```java <html> <head> <title>Add Employee Success</title> </head> <body> Employee has been added successfully. </body> </html> ``` 該文件非常簡單,僅顯示成功消息。 ## 3\. Spring MVC 表單控制器 一個非常簡單的 spring mvc 控制器,用于處理表單提交。 `EmployeeController.java` ```java @Controller @RequestMapping("/employee-module/addNew") @SessionAttributes("employee") public class EmployeeController { @Autowired EmployeeManager manager; @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) { //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"; } } ``` **要點:** 1. 控制器首先使用標準`@Controller`注解以及`@RequestMapping`注解,該注解允許通過 URL `http://localhost:8080/springmvcexample/employee-module/addNew`訪問控制器 2. 在瀏覽器中輸入該 URL 時,它將向您的 Web 應用程序發送 HTTP GET 請求。 這進而觸發`setupForm`方法的執行,該方法根據其`@RequestMapping`注解被指定為參加這種類型的請求。 3. 由于表單可能包含錯誤,因此丟失用戶在以后每次提交時提供的任何有效數據可能會帶來不便。 為了解決此問題,`@SessionAttributes`用于將員工字段保存到用戶的會話中,以便將來對員工字段的任何引用實際上都是在相同的引用上進行的,無論表單是提交兩次還是多次。 4. `setupForm`方法將`Model`對象定義為輸入參數,用于將模型數據發送到視圖(即表單)。 在處理器方法內部,創建了一個空的`EmployeeVO`對象,并將其作為屬性添加到控制器的模型對象中。 然后,控制器將執行流程返回到`addEmployee`視圖,在這種情況下,該視圖解析為我們在上面看到的`addEmployee.jsp`。 5. 填寫表單字段后,提交表單會觸發 HTTP POST 請求,該請求又會調用`submitForm`方法。 `@ModelAttribute("employee") EmployeeVO employeeVO`用于引用員工對象。 包含用戶新提交的數據的`BindingResult`對象。 如果需要訪問用戶的會話,則使用`SessionStatus`對象。 6. 在將用戶重定向到成功頁面之前,我們應該清除會話數據,因為現在它已無用。 這是通過在`SessionStatu`的對象上調用`setComplete()`方法來完成的。 7. 在數據庫中創建員工后,`submitForm`方法返回名為`redirect:addNew/success`的視圖。 視圖名稱中的`forward:`前綴用于避免稱為重復表單提交的問題。 當您在表單成功視圖中刷新網頁時,剛剛提交的表單將再次重新提交。 為避免此問題,您可以應用 post/redirect/get 設計模式,該模式建議在成功處理表單提交后重定向到另一個 URL,而不是直接返回 HTML 頁面。 ## 4\. Spring MVC 表單驗證 到現在為止,我們的示例應用程序能夠顯示表單,并接收帶有填充值的提交表單。 在現實生活中的應用中,用戶在填寫表格時會犯很多錯誤。 驗證應該始終在客戶端進行,但是為了保護數據完整性,您還應該在服務器端進行數據驗證。 驗證可以添加到應用程序中,分為兩個步驟,即首先在視圖層,然后在控制器代碼。 #### 4.1. 修改后的`addEmployee.jsp` ```java <%@ 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> <style> .error { color: #ff0000; font-weight: bold; } </style> </head> <body> <h2><spring:message code="lbl.page" text="Add New Employee" /></h2> <br/> <form:form method="post" modelAttribute="employee"> <%-- <form:errors path="*" cssClass="error" /> --%> <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> ``` 您還需要更新消息資源文件。 `messages.properties` ```java lbl.page=Add New Employee lbl.firstName=First Name lbl.lastName=Last Name lbl.email=Email Id //Error messages error.firstName=First Name can not be blank error.lastName=Last Name can not be blank error.email=Email Id can not be blank ``` #### 4.2. 修改的`SubmitForm()`方法 `EmployeeController.java` ```java @RequestMapping(method = RequestMethod.POST) public String submitForm(@ModelAttribute("employee") EmployeeVO employeeVO, BindingResult result, SessionStatus status) { //Validation code start boolean error = false; System.out.println(employeeVO); //Verifying if information is same as input by user if(employeeVO.getFirstName().isEmpty()){ result.rejectValue("firstName", "error.firstName"); error = true; } if(employeeVO.getLastName().isEmpty()){ result.rejectValue("lastName", "error.lastName"); error = true; } if(employeeVO.getEmail().isEmpty()){ result.rejectValue("email", "error.email"); error = true; } if(error) { return "addEmployee"; } //validation code ends //Store the employee information in database //manager.createNewRecord(employeeVO); //Mark Session Complete status.setComplete(); return "redirect:addNew/success"; } ``` ## 5\. Spring MVC 示例 – 演示 在測試之前,請添加其他基本文件。 ##### 5.1. Spring MVC 配置文件 `spring-servlet.xml` ```java <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 id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="messages" /> </bean> </beans> ``` #### 5.2. `web.xml` ```java <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> ``` #### 5.3. `pom.xml` ```java <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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.howtodoinjava.demo</groupId> <artifactId>springmvcexample</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>springmvcexample Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <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> <build> <finalName>springmvcexample</finalName> </build> </project> ``` 現在測試應用程序。 1)輸入 URL:`http://localhost:8080/springmvcexample/employee-module/addNew`:它將顯示空白表格。 ![Spring MVC Form Example - Blank Form](https://img.kancloud.cn/43/2c/432ce8a84fdf5451769974fd3818d242_474x263.jpg) Spring MVC 表單示例 – 空白表單 2)**填寫名字字段,然后單擊“添加員工”按鈕**。 這將列出不能將姓氏和電子郵件字段提交為空白的驗證消息。 ![Spring MVC Form Example - Validation Messages](https://img.kancloud.cn/8b/89/8b89aa93f63fb839c9f5226952cc0627_533x274.jpg) Spring MVC 表單示例 – 驗證消息 3)現在**正確填寫所有三個值,并提交表格**。 現在您將能夠看到成功消息。 ![Spring MVC Form Example - Success Message](https://img.kancloud.cn/61/50/61504b8a4e98ffd7e17b6fe41c24949a_563x213.jpg) Spring MVC 表單示例 – 成功消息 以上就是這個基本但重要的 **spring mvc crud 示例**,它涉及在 Spring MVC 中提交**表單**。 讓我繼續發布有關您的疑問和建議的信息。 [**下載源碼**](https://drive.google.com/file/d/0B7yo2HclmjI4bmVXdkhiVTJVejQ/view?usp=sharing) 學習愉快!
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看