【问题标题】:Error resolving template [], template might not exist or might not be accessible by any of the configured Template Resolvers解析模板 [] 时出错,模板可能不存在或可能无法被任何已配置的模板解析器访问
【发布时间】:2020-02-29 11:03:22
【问题描述】:

下面是我的控制器。如您所见,我想返回html 类型

@Controller
public class HtmlController {

  @GetMapping(value = "/", produces = MediaType.TEXT_HTML_VALUE)
  public Employee html() {
    return Employee.builder()
      .name("test")
      .build();
  }
}

我最初收到以下错误:

Circular view path [login]: would dispatch back to the current handler URL [/login] again

我通过关注this 帖子修复了它。

现在我收到另一个错误:

There was an unexpected error (type=Internal Server Error, status=500).
Error resolving template [], template might not exist or might not be accessible by any of the configured Template Resolvers

有人可以帮助我为什么我必须依靠 thymleaf 来提供 html 内容以及为什么会出现此错误。

【问题讨论】:

    标签: java spring-boot thymeleaf


    【解决方案1】:

    为什么我必须依赖 Thymeleaf 来提供 HTML 内容

    你没有。您可以通过其他方式做到这一点,您只需告诉 Spring 这就是您正在做的事情,即告诉它返回值是响应本身,而不是用于生成响应的视图的名称。

    正如Spring documentation 所说:

    下表描述了支持的控制器方法返回值。

    • String:通过ViewResolver实现解析并与隐式模型一起使用的视图名称 — 通过命令对象和@ModelAttribute方法确定。处理程序方法还可以通过声明Model 参数以编程方式丰富模型。

    • @ResponseBody:返回值通过HttpMessageConverter实现转换并写入响应。见@ResponseBody

    • ...

    • 任何其他返回值:任何与此表中任何先前值不匹配的返回值 [...] 都被视为视图名称(默认视图名称选择通过 RequestToViewNameTranslator适用)。

    在您的代码中,Employee 对象如何变成text/html?现在,代码属于“任何其他返回值”类别,但失败了。

    你可以,例如

    • 使用 Thymeleaf 模板(这是推荐的方式)

      @GetMapping(path = "/", produces = MediaType.TEXT_HTML_VALUE)
      public String html(Model model) { // <== changed return type, added parameter
          Employee employee = Employee.builder()
              .name("test")
              .build();
          model.addAttribute("employee", employee);
          return "employeedetail"; // view name, aka template base name
      }
      
    • String toHtml() 方法添加到Employee 然后执行:

      @GetMapping(path = "/", produces = MediaType.TEXT_HTML_VALUE)
      @ResponseBody // <== added annotation
      public String html() { // <== changed return type (HTML is text, i.e. a String)
          return Employee.builder()
              .name("test")
              .build()
              .toHtml(); // <== added call to build HTML content
      }
      

      这实际上使用了一个内置的StringHttpMessageConverter

    • 使用注册的HttpMessageConverter(不推荐)

      @GetMapping(path = "/", produces = MediaType.TEXT_HTML_VALUE)
      @ResponseBody // <== added annotation
      public Employee html() {
          return Employee.builder()
              .name("test")
              .build();
      }
      

      这当然需要您编写一个支持 text/htmlregister it 与 Spring Framework 的 HttpMessageConverter&lt;Employee&gt; 实现。

    【讨论】:

      猜你喜欢
      • 2020-06-30
      • 2014-05-28
      • 2019-07-03
      • 2018-03-05
      • 2021-05-03
      • 2022-06-16
      • 2018-07-12
      • 2018-08-30
      • 2019-12-02
      相关资源
      最近更新 更多