【发布时间】:2020-10-09 17:40:43
【问题描述】:
更新:将注释从@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>
【问题讨论】:
标签: java spring spring-mvc thymeleaf