错误解析模板[],模板可能不存在,或者任何配置的模板解析器都无法访问该模板

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

有人可以帮助我吗?为什么我必须依靠胸腺来提供html内容,为什么我会收到此错误消息。

zxofxop 回答:错误解析模板[],模板可能不存在,或者任何配置的模板解析器都无法访问该模板

  

为什么我必须依靠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();
    }
    

    这当然要求您编写一个HttpMessageConverter<Employee>实现,该实现支持Spring框架中的text/htmlregister it

本文链接:https://www.f2er.com/3168721.html

大家都在问