Java Thymeleaf控制器未渲染
更新:将注释从@RestController切换到@Controller,现在我在尝试点击时只得到一个404。我在控制器中添加了System.out.println,并看到它正在打印,所以我知道它正在进入控制器。我想它就是找不到模板Java Thymeleaf控制器未渲染,java,spring,spring-mvc,thymeleaf,Java,Spring,Spring Mvc,Thymeleaf,更新:将注释从@RestController切换到@Controller,现在我在尝试点击时只得到一个404。我在控制器中添加了System.out.println,并看到它正在打印,所以我知道它正在进入控制器。我想它就是找不到模板 @Controller @RequestMapping("/api/v1") public class UrlShorteningController { @GetMapping("/create_short_url") public String n
@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>
src/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>
模板的路径应该是src/main/resources/templates/我意识到我的编辑器没有选择视图名称。我不知道为什么,因为文件夹结构似乎是正确的。我试着将它重命名为某种形式,但它突然起了作用。不确定是否对html文件名有长度限制 您使用的是GetMapping而不是RequestMapping。如果希望提供模板,请使用RequestMapping。GetMapping仅适用于get请求,该请求解释了您接收文本字符串而不是模板的原因。尝试使用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标记!不幸的是,将它移动到那里似乎没有帮助:/相同的问题。我在过去也成功地通过get映射实现了这一点-。如果你拉那个repo,签出那个commit,然后运行它,它会站起来并返回一个类似的模板。这是错误的,@GetMapping注释只是@RequestMappingmethod=RequestMethod.GET的一个快捷方式,显示你是否用那个commit命令站起来,它可以工作。您需要替换@RestController并使用RequestMapping。RestController和RequestMapping或GetMapping的组合返回表单名称的字符串,就像我在原始问题中所做的那样。带有RequestMapping或GetMapping的控制器返回404。