<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-custom-validator-example/](https://howtodoinjava.com/spring-mvc/spring-mvc-custom-validator-example/) 在 [**spring mvc 表單提交教程**](https://howtodoinjava.com/spring/spring-mvc/spring-mvc-display-validate-and-submit-form-example/)中,我們學習了如何顯示顯示表單和提交表單數據,包括使用`BindingResult.rejectValue()`驗證輸入。 在此示例中,我們將學習為`EmployeeVO`模型對象構建更強大的驗證器。 該驗證器是 **`Validator`** 接口的自定義實現。 在此示例中,我將修改上一個教程中構建的表單提交示例所使用的代碼。 > **閱讀更多: [Spring MVC 顯示,驗證和提交表單示例](https://howtodoinjava.com/spring/spring-mvc/spring-mvc-display-validate-and-submit-form-example/)** [**下載源碼**](https://drive.google.com/file/d/0B7yo2HclmjI4WFFvOVAwNFRVV1E/view?usp=sharing) ## 自定義驗證器實現 Spring MVC 通過實現`Validator`接口的驗證器對象來支持驗證。 您可以編寫以下驗證器來檢查是否填寫了必需的表單字段。 ```java package com.howtodoinjava.demo.validator; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import com.howtodoinjava.demo.model.EmployeeVO; @Component public class EmployeeValidator implements Validator { public boolean supports(Class clazz) { return EmployeeVO.class.isAssignableFrom(clazz); } public void validate(Object target, Errors errors) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "error.firstName", "First name is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "error.lastName", "Last name is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "error.email", "Email is required."); } } ``` 在此驗證器中,您可以使用`ValidationUtils`類中的`rejectIfEmptyOrWhitespace()`和`rejectIfEmpty()`之類的實用方法來驗證所需的表單字段。 如果這些表單字段中的任何一個為空,這些方法將創建一個字段錯誤并將其綁定到該字段。 這些方法的第二個參數是屬性名稱,而第三個和第四個是錯誤代碼和默認錯誤消息。 很多時候,驗證錯誤并非特定于字段。 例如,結束日期應大于開始日期。 在這種情況下,可以使用`reject()`方法創建要綁定到`EmployeeVO`對象而不是字段的對象錯誤。 例如`errors.reject("invalid.dateDiff", "結束日期應大于開始日期。");` 要將此自定義驗證器激活為 spring 托管 bean,您需要執行以下操作之一: 1)在`EmployeeValidator`類中添加[`@Component`](https://howtodoinjava.com/spring/spring-core/how-to-use-spring-component-repository-service-and-controller-annotations/)注解,并在包含此類聲明的包上激活注解掃描。 ```java <context:component-scan base-package="com.howtodoinjava.demo" /> ``` 2)或者,您可以直接在上下文文件中注冊驗證器類 bean。 ```java <bean id="employeeValidator" class="com.howtodoinjava.demo.validator.EmployeeValidator" /> ``` ## 控制器變更 要應用此驗證器,您需要對控制器執行以下修改。 1)包括控制器類的驗證器引用,并對其進行自動標記,以確保在需要時可用。 ```java @Autowired EmployeeValidator validator; ``` 2)下一個更改是在控制器的 post 方法中,該方法在用戶提交表單時調用。 ```java @RequestMapping(method = RequestMethod.POST) public String submitForm(@ModelAttribute("employee") EmployeeVO employeeVO, BindingResult result, SessionStatus status) { //Validation code validator.validate(employeeVO, result); //Check validation errors if (result.hasErrors()) { return "addEmployee"; } //Store the employee information in database //manager.createNewRecord(employeeVO); //Mark Session Complete status.setComplete(); return "redirect:addNew/success"; } ``` 驗證方法返回后,結果參數(即`BindingResult`)將包含驗證過程的結果。 您可以使用`result.hasErrors()`方法調用檢查輸入是否有錯誤。 如果檢測到任何錯誤,您可以再次渲染表單視圖,以使用戶更正其輸入。 如果未發現錯誤,則`result.hasErrors()`將返回`false`,然后您可以簡單地處理輸入并將用戶重定向到下一個視圖。 本示例中使用的完整源代碼敵人控制器如下: ```java package com.howtodoinjava.demo.controller; 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.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.model.EmployeeVO; import com.howtodoinjava.demo.service.EmployeeManager; import com.howtodoinjava.demo.validator.EmployeeValidator; @Controller @RequestMapping("/employee-module/addNew") @SessionAttributes("employee") public class EmployeeController { @Autowired EmployeeManager manager; @Autowired EmployeeValidator validator; @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) { validator.validate(employeeVO, result); if (result.hasErrors()) { return "addEmployee"; } //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"; } } ``` [**下載源碼**](https://drive.google.com/file/d/0B7yo2HclmjI4WFFvOVAwNFRVV1E/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>

                              哎呀哎呀视频在线观看