下面是我的 Controller 。如您所见,我想返回 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 内容以及为什么我会收到此错误。
最佳答案
why I have to rely on Thymeleaf for serving HTML content
你不知道。你可以用其他方式做到这一点,你只需要告诉 Spring 这就是你正在做的事情,即告诉它返回值是响应本身,而不是用于生成响应的 View 的名称。
The next table describes the supported controller method return values.
String
: A view name to be resolved withViewResolver
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 aModel
argument.
@ResponseBody
: The return value is converted throughHttpMessageConverter
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 }
这实际上使用了内置的
StringHttpMessageConverter
.使用已注册的
HttpMessageConverter
(不推荐):@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 框架。
关于java - 解析模板 [] 时出错,模板可能不存在,或者任何已配置的模板解析器都无法访问该模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58688195/