HttpMediaTypeNotAcceptableException for MediaType HTML



我有Spring Rest控制器,如下所示:

@RestController
@RequestMapping(value = "/v1/files")
public class DataReader {
@GetMapping(value = "/", produces = MediaType.TEXT_HTML_VALUE)
public Employee readData () {
Employee employee = new Employee();
employee.setName("GG");
employee.setAddress("address");
employee.setPostCode("postal code");
return employee;
}
}

基本上,我希望这个控制器返回html内容。然而,当我从浏览器或邮递员那里点击URI时,我会得到以下异常:

There was an unexpected error (type=Not Acceptable, status=406).
Could not find acceptable representation
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:316)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:181)

方法的返回类型是对象Employee。如果您需要返回HTML内容,请选择以下任何选项

  1. 将控制器从@RestController转换为@Controller,添加spring-MVC依赖项,配置模板引擎,创建您的htmls并从控制器返回

  2. 使用Streams将HTML作为响应实体中的字节数组发送,而不是从REST控制器返回Employee对象。

为了提供html内容,如果内容是静态的,那么您可以使用控制器端点,如:

@GetMapping(value = "/")
public Employee readData () {
return "employee";
}

springboot将返回名为"employee"的静态html页面。但在您的情况下,您需要返回一个modelandview映射,以使动态数据与html呈现为:

@GetMapping(value = "/")
public Employee readData (Model model) {
Employee employee = new Employee();
employee.setName("GG");
employee.setAddress("address");
employee.setPostCode("postal code");
model.addAttribute("employee",employee)
return "employee";
}

还要从类中删除@RestController注释并添加@Controller

否则,如果您的用例要求您从REST端点返回html内容,则使用类似:

@RestController
@RequestMapping(value = "/v1/files")
public class DataReader {
@GetMapping(value = "/", produces = MediaType.TEXT_HTML_VALUE)
public Employee readData () {
// employees fetched from the data base
String html = "<HTML></head> Employee data converted to html string";
return html;
}
}

或使用return ResponseEntity.ok('<HTML><body>The employee data included as html.</body></HTML>')

相关内容

  • 没有找到相关文章

最新更新