更新:将注释从@RestController切换到@Controller,现在我只需点击http://localhost:8080/api/v1/create_short_url就可以得到404。我在控制器中添加了一个System.out.println,并看到它正在打印,所以我知道它正在进入控制器中。我觉得它只是找不到模板。
@Controller
@RequestMapping("/api/v1")
public class UrlShorteningController {
@GetMapping("/create_short_url")
public String newShortUrl(Model model) {
System.out.println("^^^^^^^");
model.addAttribute("longUrl",
new String());
return "new-short-url-form";
}请求

我有一个控制器,我希望它呈现一个HTML模板。相反,它只返回控制器的名称。我在这里做错什么了?
实际:

预期的:html页面的呈现
代码

src/main/java/com/example/urlshortener/api/UrlShorteningController.java:中的控制器
@RestController
....
@GetMapping("/create_short_url")
public String newShortUrl(Model model) {
model.addAttribute("longUrl",
new String());
return "new-short-url-form";
}build.gradle:
...
dependencies {
...
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
...
}src/main/resources/templates/new-short-url-form.html中的Thymeleaf模板
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>New Short Url</title>
</head>
<body>
<form method="POST" th:action="@{/create_short_url_thymeleaf}" th:object="${String}">
<h1>Enter a url to shorten</h1>
<input type="text" id="longUrl" th:field="*{String}"/>
</form>
</body>
</html>发布于 2020-06-19 13:20:08
src/resources/templates/new-short-url-form.html中的
胸腺模板
模板的路径应该是src/main/resources/templates/
发布于 2020-06-19 14:11:22
我意识到我的编辑没有拿起视图的名字。我不知道,为什么,因为文件夹结构似乎是正确的。我试着把它重命名为“某种形式”,但它突然起作用了。不确定html文件名顶部是否有长度限制。

发布于 2020-06-19 14:20:20
您使用的是GetMapping而不是RequestMapping。如果希望提供模板,请使用RequestMapping。GetMapping只用于get请求,这解释了为什么要接收文字字符串而不是模板。
https://stackoverflow.com/questions/62470752
复制相似问题