ZetCode

Spring Boot @ModelAttribute

最后修改于 2023 年 7 月 16 日

Spring Boot @ModelAttribute 教程展示了如何在 Spring 应用程序中使用 @ModelAttribute 注解。

Spring 是一个流行的 Java 应用程序框架,而 Spring Boot 是 Spring 的一个演进,它有助于轻松创建独立的、生产级的基于 Spring 的应用程序。

@ModelAttribute

@ModelAttribute 将方法参数或方法返回值绑定到命名的模型属性,该属性将暴露给 Web 视图。使用 @ModelAttribute 注解的方法在带有 @RequestMapping 的控制器方法之前被调用。

Spring Boot @ModelAttribute 示例

以下应用程序演示了 @ModelAttribute 的用法。它用于在应用程序中生成每日消息。消息从 properties 文件中读取。

build.gradle
...
src
├── main
│   ├── java
│   │   └── com
│   │       └── zetcode
│   │           ├── Application.java
│   │           ├── controller
│   │           │   └── MyController.java
│   │           └── service
│   │               ├── IMessageService.java
│   │               └── MessageService.java
│   └── resources
│       ├── application.properties
│       ├── static
│       │   └── index.html
│       └── templates
│           ├── pageOne.mustache
│           └── pageTwo.mustache
└── test
    ├── java
    └── resources

这是项目结构。

build.gradle
plugins {
    id 'org.springframework.boot' version '3.1.1'
    id 'io.spring.dependency-management' version '1.1.0'
    id 'java'
}

group = 'com.zetcode'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-mustache'
}

这是 Gradle 构建文件。

resources/application.properties
spring.main.banner-mode=off
logging.level.org.springframework=ERROR

messages.motd=Welcome

application.properties 是 Spring Boot 中的主要配置文件。我们关闭 Spring 横幅,并通过仅选择错误消息来减少 Spring 框架的日志记录量。

messages.motd 属性包含消息。

com/zetcode/service/IMessageService.java
package com.zetcode.service;

public interface IMessageService {

    String getMessage();
}

IMessageService 包含 getMessage 契约方法。

com/zetcode/service/MessageService.java
package com.zetcode.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class MessageService implements IMessageService {

    @Value("${messages.motd}")
    private String motd="Hello";

    @Override
    public String getMessage() {

        return motd;
    }
}

getMessage 方法的实现使用 @Value 注解从 properties 文件中检索消息。

com/zetcode/controller/MyController.java
package com.zetcode.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.zetcode.service.IMessageService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;

@Controller
public class MyController {

    private final IMessageService messageService;

    public MyController(IMessageService messageService) {
        this.messageService = messageService;
    }

    @GetMapping("/pageOne")
    public String getPageOne() {

        return "pageOne";
    }

    @GetMapping("/pageTwo")
    public String getPageTwo() {

        return "pageTwo";
    }

    @ModelAttribute("motd")
    public String message() {

        return messageService.getMessage();
    }
}

由于 MyController 使用 @Controller 注解,它成为一个 Spring MVC 控制器类。使用 @GetMapping 注解,我们将两个 URL 模式映射到 Mustache 视图。这两个模板都接收一个 motd 模型属性。

@ModelAttribute("motd")
public String message() {

    return messageService.getMessage();
}

一个使用 @ModelAttribute 注解的方法在 @RequestMapping 方法及其特化(如 @GetMapping)之前执行。从 messageService 生成的消息存储在 motd 模型属性中,并且可用于两个 Mustache 视图。

resources/templates/pageOne.mustache
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Page one</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h2>Page one</h2>

<p>
    {{ motd }}
</p>

</body>
</html>

这是 pageOne.mustache 视图。 motd 属性使用 {{ }} 语法访问。

resources/templates/pageTwo.mustache
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Page two</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>

<h2>Page two</h2>

<p>
    {{ motd }}
</p>

</body>
</html>

这是 pageTwo.mustache 视图。

resources/static/index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Home page</title>
        <meta charset="UTF-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>

    <body>
        <a href="/pageOne">Go to page one</a><br>
        <a href="/pageTwo">Go to page two</a>
    </body>

</html>

这是主页。它包含两个链接。

com/zetcode/Application.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 应用程序的入口点。

$ ./gradlew bootRun

运行应用程序后,我们可以导航到 localhost:8080

在本文中,我们展示了如何在 Spring 应用程序中使用 @ModelAttribute 注解。

作者

我叫 Jan Bodnar,是一位对编程充满热情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

列出 所有 Spring Boot 教程