<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-populate-and-validate-dropdown-example/](https://howtodoinjava.com/spring-mvc/spring-mvc-populate-and-validate-dropdown-example/) 如果您正在使用 [**Spring MVC**](https://howtodoinjava.com/category/frameworks/java-spring-tutorials/spring-mvc/) 開發的任何面向客戶的 Web 應用程序,那么您可能還需要在應用程序 UI 中的某個位置使用下拉框。 本教程將幫助您顯示預填充的下拉列表,然后驗證用戶在提交表單時是否選擇了任何值。 這篇文章是我以前關于 [**spring mvc 驗證(使用 JSR-303 注解**](https://howtodoinjava.com/spring/spring-mvc/spring-bean-validation-example-with-jsr-303-annotations/) )的繼續。 我將修改相同的源代碼。 **在此示例中**,我將顯示一個用于向系統中添加新員工的表單。 該表格將有一個下拉列表,列出所有部門。 應用程序用戶必須在提交表單之前從下拉列表中選擇一個值。 [![Spring MVC Dropdown Example - Blank Form](https://img.kancloud.cn/ad/45/ad45163766a746f010c9961ee4c65e7b_407x253.jpg)](https://howtodoinjava.com/wp-content/uploads/2015/02/Spring-MVC-Dropdown-Example-Blank-Form.png) Spring MVC 下拉菜單示例 – 空白表單 [**下載源碼**](https://drive.google.com/file/d/0B7yo2HclmjI4NE9ILW1GNDBCUGM/view?usp=sharing) ```java Table of Contents Model Classes Adding PropertyEditorSupport View layer changes for displaying Dropdown box Dropdown validation changes Test The Application ``` ## 模型類 `DepartmentVO.java` ```java package com.howtodoinjava.demo.model; public class DepartmentVO { public DepartmentVO(Integer id, String name) { super(); this.id = id; this.name = name; } private Integer id; private String name; //Setters and Getters @Override public String toString() { return "DepartmentVO [id=" + id + ", name=" + name + "]"; } } ``` `EmployeeVO.java` 此類具有`DepartmentVO`的關聯屬性。 ```java package com.howtodoinjava.demo.model; import java.io.Serializable; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; public class EmployeeVO implements Serializable { private static final long serialVersionUID = 1L; private Integer id; @NotEmpty private String firstName; private String lastName; private String email; @NotNull private DepartmentVO department; //Setters and Getters @Override public String toString() { return "EmployeeVO [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + ", department=" + department + "]"; } } ``` ## 添加`PropertyEditorSupport` 我們不會在 UI 中將`DepartmentVO`顯示為 java 對象,而是當用戶提交綁定到`Department`字段的屬性時,HTTP POST 中只會出現一個字符串值。 我們需要某種機制將字符串值轉換回`DepartmentVO`實例并注入`EmployeeVO`實例。 Spring 為此提供了`PropertyEditorSupport`類。 `DepartmentEditor.java` ```java package com.howtodoinjava.demo.convertor; import java.beans.PropertyEditorSupport; import com.howtodoinjava.demo.model.DepartmentVO; public class DepartmentEditor extends PropertyEditorSupport { //This will be called when user HTTP Post to server a field bound to DepartmentVO @Override public void setAsText(String id) { DepartmentVO d; switch(Integer.parseInt(id)) { case 1: d = new DepartmentVO(1, "Human Resource"); break; case 2: d = new DepartmentVO(2, "Finance"); break; case 3: d = new DepartmentVO(3, "Information Technology"); break; default: d = null; } this.setValue(d); } } ``` 可以,但是 spring 怎么會知道我們有此類用于轉換目的。 為此,我們必須告訴 Spring。 我們可以通過以下方式在控制器類中進行操作。 ```java @InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(DepartmentVO.class, new DepartmentEditor()); } ``` 現在,每次將表單提交到`EmployeeController`且字段綁定到`department`的字段時,`DepartmentEditor`都會用于將字符串值轉換為`DepartmentVO`實例。 `EmployeeController`的完整代碼如下。 `EmployeeController.java` ```java package com.howtodoinjava.demo.controller; import java.util.ArrayList; import java.util.List; 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.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; 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.convertor.DepartmentEditor; import com.howtodoinjava.demo.model.DepartmentVO; 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(); } @InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(DepartmentVO.class, new DepartmentEditor()); } @ModelAttribute("allDepartments") public List<DepartmentVO> populateDepartments() { ArrayList<DepartmentVO> departments = new ArrayList<DepartmentVO>(); departments.add(new DepartmentVO(-1, "Select Department")); departments.add(new DepartmentVO(1, "Human Resource")); departments.add(new DepartmentVO(2, "Finance")); departments.add(new DepartmentVO(3, "Information Technology")); return departments; } @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); System.out.println(employeeVO); // Mark Session Complete status.setComplete(); return "redirect:addNew/success"; } @RequestMapping(value = "/success", method = RequestMethod.GET) public String success(Model model) { return "addSuccess"; } } ``` 要了解有關此控制器中更多代碼段的更多信息,請參考本 [**spring mvc 顯示形式教程**](https://howtodoinjava.com/spring/spring-mvc/spring-mvc-display-validate-and-submit-form-example/) 。 ## 查看更改以顯示下拉框 要顯示下拉列表,您必須將部門的集合提供給 jsp 文件。 這是從控制器完成的。 請注意,在此示例中,我對集合進行了硬編碼。 在生產類應用程序中,您將需要動態構建此集合。 ```java @ModelAttribute("allDepartments") public List<DepartmentVO> populateDepartments() { ArrayList<DepartmentVO> departments = new ArrayList<DepartmentVO>(); departments.add(new DepartmentVO(-1, "Select Department")); departments.add(new DepartmentVO(1, "Human Resource")); departments.add(new DepartmentVO(2, "Finance")); departments.add(new DepartmentVO(3, "Information Technology")); return departments; } ``` 可以在`form:select`標記的 JSP 文件內部訪問此`allDepartments`屬性。 ```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> <!-- DROPDOWN code --> <tr> <td><spring:message code="lbl.department" text="Department" /></td> <td><form:select path="department" items="${allDepartments}" itemValue="id" itemLabel="name" /></td> <td><form:errors path="department" cssClass="error" /></td> </tr> <tr> <td colspan="3"><input type="submit" value="Add Employee"/></td> </tr> </table> </form:form> </body> </html> ``` ## 下拉驗證 為了驗證下拉框,我們使用了以下內容。 1)我們在`EmployeeVO`內的**部門**字段中使用了`@NotNull`注解。 如果字段為`null`,使用 JSR-303 的 spring 驗證將自動引發錯誤。 ```java @NotNull private DepartmentVO department; ``` 2)由于具有`@NotNull`注解,因此我們要做的就是在`department`字段中為所有意外值設置`null`。 這是在`DepartmentEditor`內部完成的,因為在進入控制器代碼之前,會調用`DepartmentEditor.setAsText()`來設置**部門**的正確值。 ```java public void setAsText(String id) { DepartmentVO d; switch(Integer.parseInt(id)) { case 1: d = new DepartmentVO(1, "Human Resource"); break; case 2: d = new DepartmentVO(2, "Finance"); break; case 3: d = new DepartmentVO(3, "Information Technology"); break; default: d = null; } this.setValue(d); } ``` **在上面的代碼中**,僅當下拉選擇值是 1,2 或 3 時; 那么只會設置部門的有效實例。 否則,部門將設置為`null`。 此`null`將引發錯誤。 ## 測試下拉菜單 1)部署應用程序并輸入 URL:`http://localhost:8080/springmvcexample/employee-module/addNew` ![Spring MVC Dropdown Example - Blank Form](https://img.kancloud.cn/ad/45/ad45163766a746f010c9961ee4c65e7b_407x253.jpg) Spring MVC 下拉菜單示例 – 空白表達 2)填寫名字并提交表格。 您將驗證消息。 ![Spring MVC Dropdown Example - Dropdown ValidationSpring MVC Dropdown Example - Dropdown Validation](https://img.kancloud.cn/05/1e/051e05197c1e54a658d37e7e07faf357_474x239.jpg) Spring MVC 下拉菜單示例 – 下拉菜單驗證 3)從列表中選擇一個部門并提交表格。 您將成功頁面。 ![Spring MVC Form Example - Success Message](https://img.kancloud.cn/61/50/61504b8a4e98ffd7e17b6fe41c24949a_563x213.jpg) Spring MVC 表單示例 – 成功消息 [**下載源碼**](https://drive.google.com/file/d/0B7yo2HclmjI4NE9ILW1GNDBCUGM/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>

                              哎呀哎呀视频在线观看