<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>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # Spring `BindingResult`教程 > 原文: [http://zetcode.com/spring/bindingresult/](http://zetcode.com/spring/bindingresult/) Spring `BindingResult`教程展示了如何使用`BindingResult`來獲取驗證結果。 Spring 是用于創建企業應用的流行 Java 應用框架。 ## `BindingResult` `BindingResult`保存驗證和綁定的結果,并包含可能發生的錯誤。 `BindingResult`必須緊隨經過驗證的模型對象之后,否則 Spring 無法驗證該對象并引發異常。 ## Spring `BindingResult`示例 以下應用驗證用戶表單,并使用`BindingResult`存儲驗證結果。 ```java pom.xml src ├───main │ ├───java │ │ └───com │ │ └───zetcode │ │ ├───config │ │ │ MyWebInitializer.java │ │ │ WebConfig.java │ │ ├───controller │ │ │ MyController.java │ │ └───form │ │ UserForm.java │ └───resources │ └───templates │ form.html │ showInfo.html └───test └───java ``` 這是項目結構。 `pom.xml` ```java <?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zetcode</groupId> <artifactId>bindingresultex</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> <spring-version>5.1.3.RELEASE</spring-version> <thymeleaf-version>3.0.11.RELEASE</thymeleaf-version> </properties> <dependencies> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.10.Final</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.3.RELEASE</version> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>${thymeleaf-version}</version> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf</artifactId> <version>${thymeleaf-version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.4.14.v20181114</version> </plugin> </plugins> </build> </project> ``` 在`pom.xml`文件中,我們具有項目依賴項。 ```java <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.10.Final</version> </dependency> ``` 我們使用`hibernate-validator`進行驗證。 `com/zetcode/config/MyWebInitializer.java` ```java package com.zetcode.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.FrameworkServlet; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; @Configuration public class MyWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return null; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{WebConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } } ``` `MyWebInitializer`初始化 Spring Web 應用。 它包含一個配置類:`WebConfig`。 `com/zetcode/config/WebConfig.java` ```java package com.zetcode.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.thymeleaf.spring5.SpringTemplateEngine; import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver; import org.thymeleaf.spring5.view.ThymeleafViewResolver; @Configuration @EnableWebMvc @ComponentScan(basePackages = {"com.zetcode"}) public class WebConfig implements WebMvcConfigurer { @Autowired private ApplicationContext applicationContext; @Bean public SpringResourceTemplateResolver templateResolver() { var templateResolver = new SpringResourceTemplateResolver(); templateResolver.setApplicationContext(applicationContext); templateResolver.setPrefix("classpath:/templates/"); templateResolver.setSuffix(".html"); return templateResolver; } @Bean public SpringTemplateEngine templateEngine() { var templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); templateEngine.setEnableSpringELCompiler(true); return templateEngine; } @Bean public ViewResolver viewResolver() { var resolver = new ThymeleafViewResolver(); var registry = new ViewResolverRegistry(null, applicationContext); resolver.setTemplateEngine(templateEngine()); registry.viewResolver(resolver); return resolver; } } ``` `WebConfig`配置 Thymeleaf 模板引擎。 Thymeleaf 模板文件位于類路徑的`templates`子目錄中。 `com/zetcode/form/UserForm.java` ```java package com.zetcode.form; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; public class UserForm { @NotBlank @Size(min=2) private String name; @NotBlank @Email private String email; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } ``` 這是一個表單 bean。 它包含一些驗證注解。 ```java @NotBlank @Size(min=2) private String name; ``` name 屬性不能為空,并且必須至少包含 2 個字符。 ```java @NotBlank @Email private String email; ``` email 屬性不能為空,并且必須是格式正確的電子郵件。 `com/zetcode/controller/MyController.java` ```java package com.zetcode.controller; import com.zetcode.form.UserForm; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.validation.Valid; @Controller public class MyController { @GetMapping(value = "/") public String form(UserForm userForm) { return "form"; } @PostMapping("/") public String checkForm(@Valid UserForm userForm, BindingResult bindingResult, RedirectAttributes atts) { if (bindingResult.hasErrors()) { return "form"; } atts.addAttribute("name", userForm.getName()); atts.addAttribute("email", userForm.getEmail()); return "redirect:/showInfo"; } @GetMapping("/showInfo") public String showInfo(@ModelAttribute("name") String name, @ModelAttribute("email") String email) { return "showInfo"; } } ``` `MyController`包含請求路徑到處理器方法的映射。 ```java @GetMapping(value = "/") public String form(UserForm userForm) { return "form"; } ``` 主頁返回一個包含表單的視圖。 `UserForm` bean 正在支持表單。 它將使用來自表單的數據進行填充。 ```java @PostMapping("/") public String checkForm(@Valid UserForm userForm, BindingResult bindingResult, RedirectAttributes atts) { ... ``` 我們用`@Valid`驗證`UserForm` bean。 驗證結果存儲在`BindingResult`中。 ```java if (bindingResult.hasErrors()) { return "form"; } ``` 如果綁定結果包含錯誤,我們將返回表格。 ```java atts.addAttribute("name", userForm.getName()); atts.addAttribute("email", userForm.getEmail()); return "redirect:/showInfo"; ``` 遵循發布后重定向模式,成功驗證后,我們將重定向到`showInfo`視圖。 為了不丟失輸入,我們將它們存儲在`RedirectAttributes`中。 ```java @GetMapping("/showInfo") public String showInfo(@ModelAttribute("name") String name, @ModelAttribute("email") String email) { return "showInfo"; } ``` `@ModelAttribute`將請求屬性`nad`放入模型對象,然后將其發送到`showInfo`視圖。 `resources/templates/form.html` ```java <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>User form</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.1/semantic.min.css" rel="stylesheet"> </head> <body> <section class="ui container"> <form action="#" class="ui form" th:action="@{/}" th:object="${userForm}" method="post"> <div class="field"> <label>Name:</label> <input type="text" th:field="*{name}"> <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</span> </div> <div class="field"> <label>Email:</label> <input type="text" th:field="*{email}"> <span th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Email Error</span> </div> <button class="ui button" type="submit">Submit</button> </form> </section> </body> </html> ``` 根頁面包含表單。 ```java <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.1/semantic.min.css" rel="stylesheet"> ``` 表單使用語義 UI 設置樣式。 ```java <form action="#" class="ui form" th:action="@{/}" th:object="${userForm}" method="post"> ``` `th:object`引用用戶表單 bean。 這不是一個類名,而是一個 Spring bean 名稱。 因此它是小寫的。 ```java <input type="text" th:field="*{name}"> ``` 輸入被映射到`userForm`的`name`屬性。 ```java <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</span> ``` 此行顯示可能的驗證錯誤。 `resources/templates/showInfo.html` ```java <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Show info</title> </head> <body> <p> Successfully added user <span th:text="${name}" th:remove="tag"></span> with email <span th:text="${email}" th:remove="tag"></span> </p> </body> </html> ``` 此視圖顯示輸入的信息。 在本教程中,我們在驗證表單時使用了`BindingResult`。 您可能也對這些相關教程感興趣: [Spring `@GetMapping`教程](/spring/getmapping/), [Spring `DefaultServlet`教程](/spring/defaultservlet/), [Spring Web 應用簡介](/articles/springwebfirst/)和 [Java 教程](/lang/java/)。
                  <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>

                              哎呀哎呀视频在线观看