【问题标题】:Trouble rendering thymeleaf with springboot用弹簧靴渲染百里香叶时遇到问题
【发布时间】:2015-11-15 21:38:54
【问题描述】:

大家好,我正在尝试运行一个简单的 springboot 应用程序。并尝试查看基本的 html,但无法呈现页面。我只能在浏览器上看到字符串,但看不到实际的 html 内容。请告诉我我做错了什么。

TestController.java:

@Controller
public class TestController {

    @RequestMapping(value="/person")
    @ResponseBody
    public String intro(){
        System.out.println("HH");
        return "index";
    }
}

MainApplication.java:

@SpringBootApplication
@ComponentScan(basePackages = "pathToMyControllerFolder")
public class MainApplication {

    public static void main(String[] args) {

            SpringApplication.run(MainApplication.class, args);
    }
}

在 spring 文档中提到的 /rsesources/template 文件夹中创建了 index.html: index.html:

<!DOCTYPE html>
<head lang="en">

    <title>Spring Framework Guru</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<h1>Hello</h1>

<h2>Fellow Spring Framework Gurus!!!</h2>
</body>
</html>

但我无法查看 html 内容,而是查看字符串索引。之前有 whitePage 标签错误并通过添加 @ComponentScan 来修复它,但现在只显示索引而不是实际的 html 内容。

当我检查控制台上的日志信息时,我注意到了这一点:

2015-11-15 13:22:51.442  INFO 11460 --- [lication.main()] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2015-11-15 13:22:51.442  INFO 11460 --- [lication.main()] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)

【问题讨论】:

    标签: java spring-mvc spring-boot


    【解决方案1】:

    删除@ResponseBody 注释。使用该注释,您从控制器返回的任何内容都是响应正文。在您的情况下,您返回 index 字符串,这就是整个响应正文。删除注释将导致index 字符串被解释为视图名称。

    【讨论】:

    • 非常感谢。那行得通.. 因此,如果打算将变量传递给我的视图并使用 html 呈现它,我不应该使用 @ResponseBody 注释而是使用模型并返回需要呈现的视图对吗?
    • @EmyItegbe 对。您可以添加 Model 作为控制器方法的属性,并在其中放入一些东西。然后只返回视图名称,作为字符串: public String intro(Model model){ model.addAtribute("attributeName", "attributeValue");返回“索引”; }
    猜你喜欢
    • 2021-12-11
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 2018-11-20
    • 2018-11-24
    相关资源
    最近更新 更多