更新:将注释从@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-29 04:47:36
尝试使用ModelAndView
@Controller
@RequestMapping("/api/v1")
public class UrlShorteningController {
@GetMapping("/create_short_url")
public ModelAndView newShortUrl() {
ModelAndView modelAndView = new ModelAndView();
System.out.println("^^^^^^^");
modelAndView.addObject("longUrl",
new String());
modelAndView.setViewName("new-short-url-form")
return modelAndView;
}并将html标记替换为<html lang="en" xmlns:th="http://www.thymeleaf.org">
https://stackoverflow.com/questions/62470752
复制相似问题