java - MediaType HTML 的 HttpMediaTypeNotAcceptableException

标签 java spring spring-boot spring-mvc spring-rest

我有 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 内容,请选择以下任一选项

  1. 将 Controller 从 @RestController 转换为 @Controller,添加 spring MVC 依赖项,配置模板引擎,创建 html 并从 Controller 返回它

  2. 不要从 REST Controller 返回 Employee 对象,而是使用 Streams 在响应实体中以字节数组形式发送 HTML。

关于java - MediaType HTML 的 HttpMediaTypeNotAcceptableException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58687457/

相关文章:

java - 忽略在 yaml 配置中为 spring boot admin 应用程序指定的斜杠字符

java - 如何按角色限制对 Spring Data REST 投影的访问?

java - 评估执行相同功能的不同条件的通用方法

java - 可以使用 ASM 将方法添加到现有的 Java 类吗?

java - 纯 Java MyBatis 映射器?

java - 由于服务类错误,Spring Boot 应用程序未启动

Java读取输入时抛出异常

java - Spring 表达式语言 - Java 8 forEach 或列表中的流

java - 使用 JSTL 访问模型对象

spring-boot - 使用 Mockito 模拟带有 @Transactional 方法的类