下面是我的控制器。如您所见,我想返回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内容,为什么我会收到此错误消息。
答案 0 :(得分: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();
}
这当然要求您编写一个HttpMessageConverter<Employee>
实现,该实现支持Spring框架中的text/html
和register it。