跳转至

Spring Boot 自动控制器

http://zetcode.com/articles/springbootautocontroller/

Spring Boot 自动化控制器展示了如何使用ViewControllerRegistry在 Spring Boot 应用中创建简单的自动化控制器。 我们的应用显示一个显示当前日期的简单页面。 我们使用 FreeMarker 作为模板引擎。

Spring 是流行的 Java 应用框架。 Spring Boot 致力于创建独立的,基于生产级别的基于 Spring 的应用,而无任何麻烦。

FreeMarker 是适用于 Web 和独立环境的服务器端 Java 模板引擎。 模板使用 FreeMarker 模板语言(FTL)编写,这是一种简单的专用语言。

ViewControllerRegistry

有时我们不需要复杂的控制器逻辑,而只想返回一个视图。 ViewControllerRegistry注册预先配置了状态代码和/或视图的简单自动化控制器。 它的addViewController()方法将视图控制器映射到给定的 URL 路径(或模式),以便使用预先配置的状态代码和视图来呈现响应。

pom.xml
src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           │   Application.java
│   │           ├───config
│   │           │       MvcConfig.java
│   │           └───controller
│   │                   MyController.java
│   └───resources
│       └───templates
│               index.ftl
└───test
    └───java
        └───com
            └───zetcode
                    HomePageTest.java

这是项目结构。 FreeMarker 模板文件的后缀为.ftl; 它们默认位于resources/templates目录中。 当 Spring Boot 在 Maven POM 文件中找到依赖关系时,它将自动配置 FreeMarker。 我们还包括一个测试文件。

pom.xml

<?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>springbootautomatedcontroller</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <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-freemarker</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

spring-boot-starter-freemarker是用于使用 FreeMarker 构建 Spring MVC 应用的启动器。 spring-boot-starter-test导入必要的测试模块。 该应用打包到一个 JAR 文件中。

com/zetcode/MvcConfig.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 MvcConfig implements WebMvcConfigurer {

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

MvcConfig类中,我们为主页配置一个视图和一个控制器。 由于我们在 Maven POM 文件中包含 FreeMarker,因此 Spring Boot 会自动将 FreeMarker 配置为模板引擎。 因此,index视图被映射到src/main/resources/templates目录中的index.ftl模板文件。

resources/templates/index.ftl

<#assign now = .now>
<!DOCTYPE html>
<html>
    <head>
        <title>Home page</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <p>Today is: ${now?string.short}</p>
    </body>
</html>

index.ftl模板文件是应用的主页。 它显示当前日期。

<#assign now = .now>

在这里,我们将当前日期时间值分配给now变量。

<p>Today is: ${now?string.short}</p>

我们以短格式打印日期。

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);
    }
}

我们设置了 Spring Boot 应用。 @SpringBootApplication注解启用自动配置和组件扫描。

com/zetcode/HomePageTest.java

package com.zetcode;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;

@RunWith(SpringRunner.class)
@SpringBootTest
public class HomePageTest {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void testHomePage() throws Exception {
        this.mockMvc.perform(get("/"))
                .andExpect(status().isOk())
                .andExpect(view().name("index"))
                .andDo(print());
    }
}

这是对主页的测试。

$ mvn spring-boot:run

我们启动该应用。

$ curl localhost:8080
<!DOCTYPE html>
<html>
    <head>
        <title>Home page</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <p>Today is: 5/21/19, 1:53 PM</p>
    </body>
</html>

使用curl工具,我们可以检索主页。

在本教程中,我们创建了一个简单的控制器,并在 Spring Boot 中进行了查看,而没有创建特定的控制器类。 我们已经使用 FreeMarker 作为模板引擎。 您可能也对相关教程感兴趣: Spring Boot FreeMarker 教程Spring Web 应用简介FreeMarker 教程Java 教程或列出所有 Spring Boot 教程


我们一直在努力

apachecn/AiLearning

【布客】中文翻译组