【问题标题】:Parsing string into an HTML file and recovering it with a @GetMapping将字符串解析为 HTML 文件并使用 @GetMapping 恢复它
【发布时间】:2021-07-06 03:08:54
【问题描述】:

我用 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 返回一个空屏幕。我究竟做错了什么?也许有更简单的方法来完成任务?

【问题讨论】:

  • 该值在别处设置。该代码也不适用于 model.addObject("code", "some_string") 。在 HTML 中添加动作是什么意思?
  • 请发布包含您的@GetMapping 的整个控制器类。

标签: java html spring-boot


【解决方案1】:

我使用 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}">

或者你可以试试 检查百里香文档

【讨论】:

    猜你喜欢
    • 2020-07-08
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 2015-01-15
    • 2011-07-03
    • 2019-12-18
    • 1970-01-01
    • 2021-12-01
    相关资源
    最近更新 更多