未加载Springboot模板文件

nlo*_*uit 5 java templates thymeleaf spring-boot

我正在编写我的第一个springboot web应用程序,其项目结构如下:

---src/main/java
           +com.example.myproject
                                +--Application.java
           +com.example.myproject.domain
                                +--Person.java
           +com.example.myproject.web
                                +--GreetingController.java
---src/main/resources
           +static
                 +--css
                 +--js
           +templates
                 +--greeting.html 
Run Code Online (Sandbox Code Playgroud)

Aplication.java

package com.example.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.setShowBanner(false);
        app.run(args);
    }
}
Run Code Online (Sandbox Code Playgroud)

GreetingController.java

package com.example.myproject.web;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class GreetingController {

    @RequestMapping("/greeting")
    public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
        model.addAttribute("name", name);
        return "greeting";
    }
}
Run Code Online (Sandbox Code Playgroud)

greeting.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <p th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

问题是当我运行项目时,在Web浏览器上键入以下URL

http://localhost:8080/greeting
Run Code Online (Sandbox Code Playgroud)

结果只显示此文本: 问候语 时应显示此文本: Hello,World!

我试图将greeting.html移出模板文件夹,但仍然不幸运.据我所知,springboot应该自动扫描组件并正确加载资源文件.

请帮忙就此问题提出建议.

Raj*_*ami 9

仅使用@Controller注释而不是@RestController注释.它运行正常.@RestController包含@Controller@ResponseBodyanotations.因此,如果您使用@RestController,您将从它映射到的方法获得返回响应.