Spring rest controller不返回html

gar*_*y69 10 spring-mvc thymeleaf spring-boot

我正在使用弹簧启动1.5.2,我的弹簧控制器看起来像这样

@RestController
@RequestMapping("/")
public class HomeController {

    @RequestMapping(method=RequestMethod.GET)
    public String index() {
        return "index";
    }

}
Run Code Online (Sandbox Code Playgroud)

当我去http:// localhost:8090/assessment /它到达我的控制器但没有返回我的index.html,它位于src/main/resources或src/main/resources/static下的maven项目中.如果我转到此URL http:// localhost:8090/assessment/index.html,它将返回我的index.html.我查看了本教程https://spring.io/guides/gs/serving-web-content/,他们使用百里香.我是否必须使用百日咳或类似的东西给我的春季休息控制器回复我的观点?

我的应用程序类看起来像这样

@SpringBootApplication
@ComponentScan(basePackages={"com.pkg.*"})
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我将thymeleaf依赖项添加到我的类路径时,我收到此错误(500响应代码)

org.thymeleaf.exceptions.TemplateInputException: Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers
Run Code Online (Sandbox Code Playgroud)

我想我确实需要百里香?我现在要尝试正确配置它.

更改我的控制器方法后返回index.html就可以了

@RequestMapping(method=RequestMethod.GET)
public String index() {
    return "index.html";
}
Run Code Online (Sandbox Code Playgroud)

我认为百里香或类似的软件可以让你放弃文件扩展名,但不确定.

Sur*_*h A 23

RestController注释从方法而不是HTML或JSP返回json.它是@ Controller和@ResponseBody的结合体.@RestController的主要目的是创建RESTful Web服务.对于返回html或jsp,只需使用@Controller注释控制器类.


kar*_*p90 8

你的例子是这样的:

您的控制器方法与您的路线"评估"

@Controller
public class HomeController {

    @RequestMapping(value = "/assessment", method = RequestMethod.GET)
    public String index() {
        return "index";
    }

}
Run Code Online (Sandbox Code Playgroud)

您在"src/main/resources/templates/index.html"中的Thymeleaf模板

<!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>Hello World!</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)