原文: http://zetcode.com/springboot/flashattribute/

Spring Boot Flash 属性教程展示了如何在 Spring Boot 应用中创建 Flash 消息。

Spring 是流行的 Java 应用框架,而 Spring Boot 是 Spring 的演进,可以帮助轻松地创建独立的,生产级的基于 Spring 的应用。

Flash 消息是用于用户通知或存储表单输入的临时数据。 它们存储在一个会话中,并且一旦检索就消失。

使用RedirectAttributesaddFlashAttribute()在 Spring 中将 Flash 消息创建为 Flash 属性。 它们与RedirectView结合使用。

Spring Boot Flash 属性示例

在以下应用中,我们创建用于通知和记住表单输入值的 Flash 属性。 我们有一个带有两个输入的表格。 如果输入值不符合验证标准,则应用将重定向到表单页面并显示错误消息; 这些消息作为 Flash 属性发送。

此外,还可以记住表单的正确值。

  1. src
  2. ├───main
  3. ├───java
  4. └───com
  5. └───zetcode
  6. Application.java
  7. └───controller
  8. MyController.java
  9. └───resources
  10. └───templates
  11. index.html
  12. showMessage.html
  13. └───test
  14. └───java

这是 Spring 应用的项目结构。

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  5. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  6. <modelVersion>4.0.0</modelVersion>
  7. <groupId>com.zetcode</groupId>
  8. <artifactId>springflashmessage</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <properties>
  11. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  12. <maven.compiler.source>11</maven.compiler.source>
  13. <maven.compiler.target>11</maven.compiler.target>
  14. </properties>
  15. <parent>
  16. <groupId>org.springframework.boot</groupId>
  17. <artifactId>spring-boot-starter-parent</artifactId>
  18. <version>2.1.1.RELEASE</version>
  19. </parent>
  20. <dependencies>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-web</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.hibernate</groupId>
  31. <artifactId>hibernate-validator</artifactId>
  32. <version>6.0.13.Final</version>
  33. </dependency>
  34. </dependencies>
  35. <build>
  36. <plugins>
  37. <plugin>
  38. <groupId>org.springframework.boot</groupId>
  39. <artifactId>spring-boot-maven-plugin</artifactId>
  40. </plugin>
  41. </plugins>
  42. </build>
  43. </project>

这是 Maven pom.xml文件。 我们使用spring-boot-starter-thymeleaf与 Thymeleaf 进行模板化,并使用hibernate-validator进行表单数据验证。

com/zetcode/controller/MyController.java

  1. package com.zetcode.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.ui.Model;
  4. import org.springframework.validation.annotation.Validated;
  5. import org.springframework.web.bind.annotation.ExceptionHandler;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RequestParam;
  8. import org.springframework.web.context.request.WebRequest;
  9. import org.springframework.web.servlet.ModelAndView;
  10. import org.springframework.web.servlet.mvc.support.RedirectAttributes;
  11. import org.springframework.web.servlet.view.RedirectView;
  12. import org.thymeleaf.util.StringUtils;
  13. import javax.validation.ConstraintViolationException;
  14. import javax.validation.constraints.Size;
  15. import java.util.ArrayList;
  16. import java.util.HashMap;
  17. import java.util.Map;
  18. @Controller
  19. @Validated
  20. public class MyController {
  21. @RequestMapping("/")
  22. public String index(Model model) {
  23. return "index";
  24. }
  25. @RequestMapping("/message")
  26. public ModelAndView message(@RequestParam @Size(min = 2, max = 255) String name,
  27. @RequestParam @Size(min = 2, max = 255) String occupation) {
  28. var msg = String.format("%s is a %s", name, occupation);
  29. Map<String, Object> params = new HashMap<>();
  30. params.put("message", msg);
  31. return new ModelAndView("showMessage", params);
  32. }
  33. @ExceptionHandler(ConstraintViolationException.class)
  34. public RedirectView handleError(ConstraintViolationException ex,
  35. WebRequest request,
  36. RedirectAttributes atts) {
  37. var name = request.getParameter("name");
  38. var occupation = request.getParameter("occupation");
  39. var errorMessages = new ArrayList<String>();
  40. var violations = ex.getConstraintViolations();
  41. violations.forEach(violation -> {
  42. var error = String.format("%s: %s", violation.getPropertyPath(),
  43. violation.getMessage());
  44. errorMessages.add(error);
  45. });
  46. if (!StringUtils.isEmptyOrWhitespace(name)) {
  47. atts.addFlashAttribute("name", name);
  48. }
  49. if (!StringUtils.isEmptyOrWhitespace(occupation)) {
  50. atts.addFlashAttribute("occupation", occupation);
  51. }
  52. atts.addFlashAttribute("messages", errorMessages);
  53. var redirectView = new RedirectView("/");
  54. return redirectView;
  55. }
  56. }

这是MyController。 它响应来自客户端的请求。 它找出当前日期和时间,并将处理过程解析为showMessage.ftl模板,并将其传递给数据。

  1. @Controller
  2. @Validated
  3. public class MyController {

@Validated注解验证带注解的请求参数。 在我们的例子中,我们使用两个@Size注解。

  1. @RequestMapping("/")
  2. public String index(Model model) {
  3. return "index";
  4. }

根页面返回索引视图,该视图将表单发送给客户端。

  1. @RequestMapping("/message")
  2. public ModelAndView message(@RequestParam @Size(min = 2, max = 255) String name,
  3. @RequestParam @Size(min = 2, max = 255) String occupation) {
  4. var msg = String.format("%s is a %s", name, occupation);
  5. Map<String, Object> params = new HashMap<>();
  6. params.put("message", msg);
  7. return new ModelAndView("showMessage", params);
  8. }

此操作响应表单提交。 两个输入参数,名称和职业用@Size注解。 如果一切正常,将根据参数构建一条消息,并使用showMessage视图将其发送到客户端。

  1. @ExceptionHandler(ConstraintViolationException.class)
  2. public RedirectView handleError(ConstraintViolationException ex,
  3. WebRequest request,
  4. RedirectAttributes atts) {

如果输入参数未能通过验证,则会抛出ConstraintViolationException。 我们在提供的异常处理器中对异常做出反应。

  1. var name = request.getParameter("name");
  2. var occupation = request.getParameter("occupation");

我们得到了请求参数。 它们用于保留正确的表单输入值。

  1. var errorMessages = new ArrayList<String>();
  2. var violations = ex.getConstraintViolations();
  3. violations.forEach(violation -> {
  4. var error = String.format("%s: %s", violation.getPropertyPath(),
  5. violation.getMessage());
  6. errorMessages.add(error);
  7. });

我们得到约束违例并建立错误消息列表。 错误消息将显示在表单上方的索引表单页面中。

  1. if (!StringUtils.isEmptyOrWhitespace(name)) {
  2. atts.addFlashAttribute("name", name);
  3. }
  4. if (!StringUtils.isEmptyOrWhitespace(occupation)) {
  5. atts.addFlashAttribute("occupation", occupation);
  6. }

如果填充的输入参数不为空并且不仅包含空格,则将它们与addFlashAttribute()一起存储为 Flash 属性。

  1. atts.addFlashAttribute("messages", errorMessages);

错误消息存储为 Flash 属性。

  1. var redirectView = new RedirectView("/");
  2. return redirectView;

我们使用RedirectView重定向到表单页面。

templates/index.html

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Home page</title>
  6. <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.1/semantic.min.css"
  7. rel="stylesheet">
  8. </head>
  9. <body>
  10. <section class="ui container">
  11. <ul th:each="message : ${messages}">
  12. <li th:text="${message}" class="ui error message" />
  13. </ul>
  14. <form class="ui form" action="message" method="post">
  15. <div class="field">
  16. <label>Name:</label>
  17. <input type="text" name="name" th:value="${name}">
  18. </div>
  19. <div class="field">
  20. <label>Occupation:</label>
  21. <input type="text" name="occupation" th:value="${occupation}">
  22. </div>
  23. <button class="ui button" type="submit">Send</button>
  24. </form>
  25. </section>
  26. <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.1/semantic.min.js"></script>
  27. </body>
  28. </html>

这是主页模板。 它发送带有两个输入的表单:名称和职业。 样式是使用语义 UI 库完成的。

  1. <ul th:each="message : ${messages}">
  2. <li th:text="${message}" class="ui error message" />
  3. </ul>

如果有任何错误消息,将显示它们。

templates/showMessage.html

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Message</title>
  6. </head>
  7. <body>
  8. <p th:text="${message}"/>
  9. </body>
  10. </html>

成功处理表单后,showMessage模板会显示一条消息。

com/zetcode/Application.java

  1. package com.zetcode;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class Application {
  6. public static void main(String[] args) {
  7. SpringApplication.run(Application.class, args);
  8. }
  9. }

Application是设置 Spring Boot 应用的入口。

在本教程中,我们展示了如何在 Spring 应用中使用 flash 属性。 您可能也对相关教程感兴趣: Spring Boot @RestController教程Spring Boot @ExceptionHandler教程Spring Boot 上传文件Spring Boot @RequestParam教程Java 教程