有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

解析模板[]时发生java错误,模板可能不存在,或者任何已配置的模板解析程序都无法访问该模板

下面是我的控制器。如您所见,我想返回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

有人能帮我为什么我必须依赖ThymalLeaf来提供html内容以及为什么我会遇到这个错误吗


共 (1) 个答案

  1. # 1 楼答案

    why I have to rely on Thymeleaf for serving HTML content

    你不需要。你可以用其他方式来做,你只需要告诉Spring你正在做的事情,也就是说,告诉它返回值是响应本身,而不是用来生成响应的视图的名称

    正如Spring documentation所说:

    The next table describes the supported controller method return values.

    • String: A view name to be resolved with ViewResolver implementations and used together with the implicit model — determined through command objects and @ModelAttribute methods. The handler method can also programmatically enrich the model by declaring a Model argument.

    • @ResponseBody: The return value is converted through HttpMessageConverter implementations and written to the response. See @ResponseBody.

    • ...

    • Any other return value: Any return value that does not match any of the earlier values in this table [...] is treated as a view name (default view name selection through RequestToViewNameTranslator applies).

    在您的代码中,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
      }
      

      这实际上使用了一个内置的^{}

    • 使用注册的^{}(不推荐)

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

      当然,这需要您编写一个HttpMessageConverter<Employee>实现,它支持text/html,并且register it支持Spring框架