【问题标题】:HttpMediaTypeNotAcceptableException for MediaType HTMLMediaType HTML 的 HttpMediaTypeNotAcceptableException
【发布时间】:2020-02-29 10:00:39
【问题描述】:

我有 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)

【问题讨论】:

  • 如果你想让当前代码工作,你需要做两件事,1.) 将方法返回类型更改为字符串 2.) return employee.toString(()
  • 第一件事是它是一个RestController,因此它作为简单的表示。如果您想以 html 形式提供内容,请更改为 @Controller

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


【解决方案1】:

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

  1. 将你的控制器从@RestController转换成@Controller,添加spring MVC依赖,配置模板引擎,创建你的html并从控制器返回

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

【讨论】:

  • 感谢您的回复。您能否分享一些示例代码或参考一些链接。
【解决方案2】:

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

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

springboot 将返回名为“employee”的静态 html 页面。但在您的情况下,您需要返回一个模型和视图地图,以使动态数据与 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('&lt;HTML&gt;&lt;body&gt;The employee data included as html.&lt;/body&gt;&lt;/HTML&gt;')

【讨论】:

  • 是的,我的用例是从 Rest 端点返回 Html。所以你的意思是我们必须手动将 Object 数据转换为 Html,然后将 html 作为字符串返回。
  • @user2603985 是的,这是执行此操作的一种方式。当您提供作为 TEXT_HTML_VALUE 的生产参数时,它需要一个等效于 TEXT_HTML 的字符串。
猜你喜欢
  • 1970-01-01
  • 2011-09-17
  • 1970-01-01
  • 1970-01-01
  • 2011-11-04
  • 1970-01-01
  • 2015-11-14
  • 2018-02-07
  • 2013-09-29
相关资源
最近更新 更多