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

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Spring Boot Flash 屬性 > 原文: [http://zetcode.com/springboot/flashattribute/](http://zetcode.com/springboot/flashattribute/) Spring Boot Flash 屬性教程展示了如何在 Spring Boot 應用中創建 Flash 消息。 Spring 是流行的 Java 應用框架,而 Spring Boot 是 Spring 的演進,可以幫助輕松地創建獨立的,生產級的基于 Spring 的應用。 Flash 消息是用于用戶通知或存儲表單輸入的臨時數據。 它們存儲在一個會話中,并且一旦檢索就消失。 使用`RedirectAttributes`的`addFlashAttribute()`在 Spring 中將 Flash 消息創建為 Flash 屬性。 它們與`RedirectView`結合使用。 ## Spring Boot Flash 屬性示例 在以下應用中,我們創建用于通知和記住表單輸入值的 Flash 屬性。 我們有一個帶有兩個輸入的表格。 如果輸入值不符合驗證標準,則應用將重定向到表單頁面并顯示錯誤消息; 這些消息作為 Flash 屬性發送。 此外,還可以記住表單的正確值。 ```java src ├───main │ ├───java │ │ └───com │ │ └───zetcode │ │ │ Application.java │ │ └───controller │ │ MyController.java │ │ │ └───resources │ └───templates │ index.html │ showMessage.html └───test └───java ``` 這是 Spring 應用的項目結構。 `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>springflashmessage</artifactId> <version>1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.1.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.13.Final</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ``` 這是 Maven `pom.xml`文件。 我們使用`spring-boot-starter-thymeleaf`與 Thymeleaf 進行模板化,并使用`hibernate-validator`進行表單數據驗證。 `com/zetcode/controller/MyController.java` ```java package com.zetcode.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.view.RedirectView; import org.thymeleaf.util.StringUtils; import javax.validation.ConstraintViolationException; import javax.validation.constraints.Size; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; @Controller @Validated public class MyController { @RequestMapping("/") public String index(Model model) { return "index"; } @RequestMapping("/message") public ModelAndView message(@RequestParam @Size(min = 2, max = 255) String name, @RequestParam @Size(min = 2, max = 255) String occupation) { var msg = String.format("%s is a %s", name, occupation); Map<String, Object> params = new HashMap<>(); params.put("message", msg); return new ModelAndView("showMessage", params); } @ExceptionHandler(ConstraintViolationException.class) public RedirectView handleError(ConstraintViolationException ex, WebRequest request, RedirectAttributes atts) { var name = request.getParameter("name"); var occupation = request.getParameter("occupation"); var errorMessages = new ArrayList<String>(); var violations = ex.getConstraintViolations(); violations.forEach(violation -> { var error = String.format("%s: %s", violation.getPropertyPath(), violation.getMessage()); errorMessages.add(error); }); if (!StringUtils.isEmptyOrWhitespace(name)) { atts.addFlashAttribute("name", name); } if (!StringUtils.isEmptyOrWhitespace(occupation)) { atts.addFlashAttribute("occupation", occupation); } atts.addFlashAttribute("messages", errorMessages); var redirectView = new RedirectView("/"); return redirectView; } } ``` 這是`MyController`。 它響應來自客戶端的請求。 它找出當前日期和時間,并將處理過程解析為`showMessage.ftl`模板,并將其傳遞給數據。 ```java @Controller @Validated public class MyController { ``` `@Validated`注解驗證帶注解的請求參數。 在我們的例子中,我們使用兩個`@Size`注解。 ```java @RequestMapping("/") public String index(Model model) { return "index"; } ``` 根頁面返回索引視圖,該視圖將表單發送給客戶端。 ```java @RequestMapping("/message") public ModelAndView message(@RequestParam @Size(min = 2, max = 255) String name, @RequestParam @Size(min = 2, max = 255) String occupation) { var msg = String.format("%s is a %s", name, occupation); Map<String, Object> params = new HashMap<>(); params.put("message", msg); return new ModelAndView("showMessage", params); } ``` 此操作響應表單提交。 兩個輸入參數,名稱和職業用`@Size`注解。 如果一切正常,將根據參數構建一條消息,并使用`showMessage`視圖將其發送到客戶端。 ```java @ExceptionHandler(ConstraintViolationException.class) public RedirectView handleError(ConstraintViolationException ex, WebRequest request, RedirectAttributes atts) { ``` 如果輸入參數未能通過驗證,則會拋出`ConstraintViolationException`。 我們在提供的異常處理器中對異常做出反應。 ```java var name = request.getParameter("name"); var occupation = request.getParameter("occupation"); ``` 我們得到了請求參數。 它們用于保留正確的表單輸入值。 ```java var errorMessages = new ArrayList<String>(); var violations = ex.getConstraintViolations(); violations.forEach(violation -> { var error = String.format("%s: %s", violation.getPropertyPath(), violation.getMessage()); errorMessages.add(error); }); ``` 我們得到約束違例并建立錯誤消息列表。 錯誤消息將顯示在表單上方的索引表單頁面中。 ```java if (!StringUtils.isEmptyOrWhitespace(name)) { atts.addFlashAttribute("name", name); } if (!StringUtils.isEmptyOrWhitespace(occupation)) { atts.addFlashAttribute("occupation", occupation); } ``` 如果填充的輸入參數不為空并且不僅包含空格,則將它們與`addFlashAttribute()`一起存儲為 Flash 屬性。 ```java atts.addFlashAttribute("messages", errorMessages); ``` 錯誤消息存儲為 Flash 屬性。 ```java var redirectView = new RedirectView("/"); return redirectView; ``` 我們使用`RedirectView`重定向到表單頁面。 `templates/index.html` ```java <!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Home page</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"> <ul th:each="message : ${messages}"> <li th:text="${message}" class="ui error message" /> </ul> <form class="ui form" action="message" method="post"> <div class="field"> <label>Name:</label> <input type="text" name="name" th:value="${name}"> </div> <div class="field"> <label>Occupation:</label> <input type="text" name="occupation" th:value="${occupation}"> </div> <button class="ui button" type="submit">Send</button> </form> </section> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.1/semantic.min.js"></script> </body> </html> ``` 這是主頁模板。 它發送帶有兩個輸入的表單:名稱和職業。 樣式是使用語義 UI 庫完成的。 ```java <ul th:each="message : ${messages}"> <li th:text="${message}" class="ui error message" /> </ul> ``` 如果有任何錯誤消息,將顯示它們。 `templates/showMessage.html` ```java <!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Message</title> </head> <body> <p th:text="${message}"/> </body> </html> ``` 成功處理表單后,`showMessage`模板會顯示一條消息。 `com/zetcode/Application.java` ```java package com.zetcode; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` `Application`是設置 Spring Boot 應用的入口。 在本教程中,我們展示了如何在 Spring 應用中使用 flash 屬性。 您可能也對相關教程感興趣: [Spring Boot `@RestController`教程](/sprinboot/restcontroller/), [Spring Boot `@ExceptionHandler`教程](/springboot/exceptionhandler/), [Spring Boot 上傳文件](/springboot/uploadfile/), [Spring Boot `@RequestParam`教程](/springboot/requestparam/), [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>

                              哎呀哎呀视频在线观看