【发布时间】:2020-03-06 02:23:51
【问题描述】:
在 Thymeleaf 中,触发 index.html 页面(存在于资源的模板文件夹中)在应用程序的 Main 类中提供新的 @RequestMapping 方法不起作用(输出字符串而不是呈现 HTML 页面),而是创建一个单独的具有相同 @RequestMapping 方法的 @Controller 类正在触发所需的 UI。
方法一
Main类中的@RequestMapping方法
package com.personal.boot.spring.helloworld;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class HelloworldApplication {
public static void main(String[] args) {
SpringApplication.run(HelloworldApplication.class, args);
}
@RequestMapping(value = "/index")
public String index() {
return "index";
}
}
现在,对 /index 的 get 请求将“index”输出为字符串
方法二
单独的@Controller 类中的@RequestMapping 方法
package com.personal.boot.spring.helloworld.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class WebController {
@RequestMapping(value = "/index")
public String index() {
return "index";
}
}
现在,对 /index 的 get 请求会在模板文件夹中呈现 index.html 页面。
为什么会这样?请帮忙。
【问题讨论】:
-
尝试用
@Controller而不是@RestController注释HelloworldApplication -
@caco3 有效。你能详细说明一下吗?
@RestController确实包含@Controller的功能对吧? -
我发现这个链接解释了差异。不过谢谢你。link
-
没问题。您可能还想查看Spring MVC documentation。来自链接:“@RestController 是一个组合注解,它本身使用@Controller 和@ResponseBody 进行元注解,以指示一个控制器,其每个方法都继承了类型级别的@ResponseBody 注解,因此,直接写入响应正文与视图分辨率以及使用 HTML 模板进行渲染"
标签: java spring-boot web-applications