Spring MVC Data and Thymeleaf – Spring MVC数据和Thymeleaf

最后修改: 2020年 4月 10日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

In this tutorial, we’ll talk about different ways to access Spring MVC data using Thymeleaf.

在本教程中,我们将讨论使用Thymeleaf访问Spring MVC数据的不同方法。

We’ll start by creating an email template using Thymeleaf, and we’ll enhance it with data from our Spring application.

我们将首先使用Thymeleaf创建一个电子邮件模板,然后用Spring应用程序的数据来增强它。

2. Project Setup

2.项目设置

First, we’ll need to add our Thymeleaf dependency:

首先,我们需要添加我们的Thymeleaf依赖性

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>2.7.2</version>
</dependency>

Second, let’s include the Spring Boot web starter:

第二,让我们包括Spring Boot web starter

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.7.2</version>
</dependency>

This dependency provides us with REST support that we’ll later use to create some endpoints.

这个依赖性为我们提供了REST支持,我们以后会用它来创建一些端点。

We’ll create a few Thymeleaf templates to cover our example cases and store them in resources/mvcdata. Each section of the tutorial will implement a different template:

我们将创建一些Thymeleaf模板来涵盖我们的示例案例,并将它们存储在resources/mvcdata中。本教程的每个部分将实现一个不同的模板。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
    <!-- data -->
</html>

Lastly, we’ll need to implement a controller class where we will store our business logic:

最后,我们需要实现一个控制器类,在这里我们将存储我们的业务逻辑。

@Controller
public class EmailController {
    private ServletContext servletContext;

    public EmailController(ServletContext servletContext) {
        this.servletContext = servletContext;
    }
}

Our controller class won’t always depend on the servlet context, but we’re adding it here so we can demonstrate a specific Thymeleaf feature later on.

我们的控制器类并不总是依赖于servlet上下文,但我们在这里添加它,以便以后可以演示一个特定的Thymeleaf功能。

3. Model Attributes

3.模型属性

Model attributes are used inside controller classes that prepare the data for rendering inside a view.

模型属性在控制器类中使用,这些类为视图中的渲染准备数据

One way we can add attributes to our model is to require an instance of Model as a parameter in a controller method.

我们可以为我们的模型添加属性的一种方式是要求一个Model的实例作为控制器方法的参数。

Let’s pass our emailData as an attribute:

让我们把我们的emailData作为一个属性来传递。

@GetMapping(value = "/email/modelattributes")
public String emailModel(Model model) {
    model.addAttribute("emailData", emailData);
    return "mvcdata/email-model-attributes";
}

Spring will then inject an instance of Model for us when /email/modelattributes is requested.

/email/modelattributes被请求时,Spring将为我们注入一个Model的实例。

Then, we can refer to our emailData model attribute in a Thymeleaf expression:

然后,我们可以在Thymeleaf表达式中引用我们的emailData模型属性。

<p th:text="${emailData.emailSubject}">Subject</p>

Another way we can do it is by telling our Spring container what attribute is required in our view by using @ModelAttribute:

另一种方法是通过使用@ModelAttribute来告诉我们的Spring容器在视图中需要什么属性。

@ModelAttribute("emailModelAttribute")
EmailData emailModelAttribute() {
    return emailData;
}

And then we can represent the data in our view as:

然后我们可以在我们的视图中表示数据为。

<p th:each="emailAddress : ${emailModelAttribute.getEmailAddresses()}">
    <span th:text="${emailAddress}"></span>
</p>

For more examples on Model data, please check out our Model, ModelMap, and ModelView in Spring MVC tutorial.

有关模型数据的更多示例,请查看我们的Spring MVC中的模型、ModelMap和ModelView教程。

4. Request Parameters

4.请求参数

Another way of accessing data is by request parameters:

另一种访问数据的方式是通过请求参数。

@GetMapping(value = "/email/requestparameters")
public String emailRequestParameters(
    @RequestParam(value = "emailsubject") String emailSubject) {
    return "mvcdata/email-request-parameters";
}

Meanwhile, in our template we’ll need to specify which parameter contains the data by using the keyword param:

同时,在我们的模板中,我们需要通过使用关键字param来指定哪一个参数包含数据

<p th:text="${param.emailsubject}"></p>

We can also have multiple request parameters with the same name:

我们也可以有多个同名的请求参数。

@GetMapping(value = "/email/requestparameters")
public String emailRequestParameters(
    @RequestParam(value = "emailsubject") String emailSubject,
    @RequestParam(value = "emailaddress") String emailAddress1,
    @RequestParam(value = "emailaddress") String emailAddress2) {
    return "mvcdata/email-request-parameters";
}

Then, we’ll have two options to show the data.

然后,我们将有两个选项来显示数据。

First, we can use th:each to go through each parameter with the same name:

首先,我们可以使用th:each来浏览每个同名的参数。

<p th:each="emailaddress : ${param.emailaddress}">
    <span th:text="${emailaddress}"></span>
</p>

Second, we can use the index of our parameter array:

第二,我们可以使用我们的参数数组的索引。

<p th:text="${param.emailaddress[0]}"></p>
<p th:text="${param.emailaddress[1]}"></p>

5. Session Attributes

5.会议属性

Or, we can place our data in an HttpSession attribute:

或者,我们可以将我们的数据放在一个HttpSession属性中。

@GetMapping("/email/sessionattributes")
public String emailSessionAttributes(HttpSession httpSession) {
    httpSession.setAttribute("emaildata", emailData);
    return "mvcdata/email-session-attributes";
}

Then, similarly to request parameters, we can use the session keyword:

然后,与请求参数类似,我们可以使用session关键字。

<p th:text="${session.emaildata.emailSubject}"></p>

6. ServletContext Attributes

6.ServletContext属性

With ServletContext, we won’t be able to use an expression to access emailData‘s properties.

有了ServletContext,我们将无法使用表达式来访问emailData的属性。

To work around this we’ll pass each value as a separate attribute:

为了解决这个问题,我们将把每个值作为一个单独的属性来传递。

@GetMapping("/email/servletcontext")
public String emailServletContext() {
    servletContext.setAttribute("emailsubject", emailData.getEmailSubject());
    servletContext.setAttribute("emailcontent", emailData.getEmailBody());
    servletContext.setAttribute("emailaddress", emailData.getEmailAddress1());
    servletContext.setAttribute("emaillocale", emailData.getEmailLocale());
    return "mvcdata/email-servlet-context";
}

And then, we can retrieve each via the servletContext variable:

然后,我们可以通过servletContext变量来检索每个变量:

<p th:text="${#servletContext.getAttribute('emailsubject')}"></p>

7. Beans

7.Bean

Finally, we can also provide data using context beans:

最后,我们还可以使用上下文Bean来提供数据。

@Bean
public EmailData emailData() {
    return new EmailData();
}

Thymeleaf allows bean access using @beanName syntax:

Thymeleaf允许使用@beanName语法访问bean。

<p th:text="${@emailData.emailSubject}"></p>

8. Conclusion

8.结语

In this small tutorial, we learned how to access data through Thymeleaf.

在这个小教程中,我们学习了如何通过Thymeleaf访问数据。

First, we added the proper dependencies. And second, we implemented some REST methods so we can pass data to our template.

首先,我们添加了适当的依赖性。其次,我们实现了一些REST方法,这样我们就可以向我们的模板传递数据。

As always, the code is available over on GitHub.

像往常一样,代码可在GitHub上获得