更新:将注释从@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中的胸腺模板
<!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>
答案 0 :(得分:1)
src / resources / templates / new-short-url-form.html中的胸腺模板
模板的路径应为src / main / resources / templates /
答案 1 :(得分:0)
答案 2 :(得分:0)
您使用的是GetMapping
而不是RequestMapping
。如果您希望提供模板,请使用RequestMapping
。 GetMapping
仅用于获取请求,该请求说明了为什么收到文字字符串而不是模板的原因。
答案 3 :(得分:0)
尝试使用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">