ZetCode

Spring Boot ViewControllerRegistry

最后修改于 2023 年 8 月 2 日

在本文中,我们将展示如何使用 ViewControllerRegistry 创建简单路由。

Spring 是一个流行的 Java 应用程序框架,用于创建企业应用程序。Spring Boot 是 Spring 框架的演进,它有助于以最小的 effort 创建基于 Spring 的独立、生产级应用程序。

ViewControllerRegistry

ViewControllerRegistry 允许创建简单的自动化控制器,这些控制器预先配置了状态码和/或视图。

Spring Boot ViewControllerRegistry 示例

在下面的示例中,我们使用 ViewControllerRegistry 创建一个简单的路由。

build.gradle
...
src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           │   Application.java
│   │           └───config
│   │                   AppConfig.java
│   └───resources
│       ├───static
│       │       index.html
│       └───templates
│               hello.html
└───test
    └───java

这是项目结构。

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-thymeleaf'
}

spring-boot-starter-web 是一个用于构建 Web(包括 RESTful)应用程序的启动器,使用 Spring MVC。它使用 Tomcat 作为默认的嵌入式容器。spring-boot-starter-thymeleaf 是一个用于构建使用 Thymeleaf 视图的 MVC Web 应用程序的启动器。

com/zetcode/config/AppConfig.java
package com.zetcode.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class AppConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/hello").setViewName("hello");
    }
}

AppConfig 中,我们使用 ViewControllerRegistryaddViewController 方法注册一个新路由。

resources/templates/hello.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello page</title>
</head>
<body>

<p>
    Hello there
</p>

</body>
</html>

hello.html 视图显示一条简单的消息。

resources/static/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home page</title>
</head>
<body>
<p>
    This is home page. Go to <a href="hello">hello page</a>
</p>

</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 应用程序。@SpringBootApplication 启用了自动配置和组件扫描。

$ ./gradlew bootRun

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

在本文中,我们展示了如何使用 Spring ViewControllerRegistry 创建简单路由。

作者

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

列出 所有 Spring Boot 教程