首页 > 解决方案 > 将字符串解析为 HTML 文件并使用 @GetMapping 恢复它

问题描述

我用 Spring Initilizr 创建了一个项目。我正在尝试将字符串解析为“code.html”文件并使用@GetMapping 恢复它。这是文件:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Code</title>
</head>
<body>
    <pre>
        <p th:text="${code}">
    </pre>
</body>
</html>

这是方法:

@GetMapping("/code")
public ModelAndView getHTML(HttpServletResponse response) {
    response.addHeader("Content-Type", "text/html");
    ModelAndView model = new ModelAndView();
    model.addObject("code", code.getCode());
    model.setViewName("code.html");

    return model;
}

(我有一个单独的代码类,所以 code.getCode() 只返回一个字符串。)

不幸的是,http://localhost:8080/code返回一个空屏幕。我究竟做错了什么?也许有更简单的方法来完成任务?

标签: javahtmlspring-boot

解决方案


我使用 springboot 和 thymeleft

也许您只需要发送代码中的视图

像这样

    @GetMapping("/code")
public ModelAndView getHTML(HttpServletResponse response,Model model) {
model.addAtributte("key", "code");
    return new ModelAndView ("templates/code");
}

该模型与视图一起提供

在 html 中试试这个

<p th:text="${key}">

或者您可以尝试 <th:block> 检查百里香文档


推荐阅读