我有 Spring Rest Controller ,如下:
@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;
}
}
基本上,我希望这个 Controller 返回 html 内容。但是,当我从浏览器或 postman 点击 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 内容,请选择以下任一选项
将 Controller 从
@RestController
转换为@Controller
,添加 spring MVC 依赖项,配置模板引擎,创建 html 并从 Controller 返回它不要从 REST Controller 返回 Employee 对象,而是使用 Streams 在响应实体中以字节数组形式发送 HTML。
关于java - MediaType HTML 的 HttpMediaTypeNotAcceptableException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58687457/