Thymeleaf控制器未渲染

时间:2020-06-19 12:53:02

标签: java spring spring-mvc thymeleaf

更新:将注释从@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";
}

请求 enter image description here


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

实际Actual

预期: html页面的呈现

代码

enter image description here

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>

4 个答案:

答案 0 :(得分:1)

src / resources / templates / new-short-url-form.html中的

胸腺模板

模板的路径应为src / main / resources / templates /

答案 1 :(得分:0)

我意识到编辑器没有选择视图名称。我不知道为什么,因为文件夹结构似乎正确。我尝试将其重命名为“某种形式”,但突然生效。不确定是否对html文件名有长度限制。

enter image description here

答案 2 :(得分:0)

您使用的是GetMapping而不是RequestMapping。如果您希望提供模板,请使用RequestMappingGetMapping仅用于获取请求,该请求说明了为什么收到文字字符串而不是模板的原因。

答案 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">

相关问题