首页 > 解决方案 > MediaType HTML 的 HttpMediaTypeNotAcceptableException

问题描述

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

标签: javaspringspring-bootspring-mvcspring-rest

解决方案


为了提供 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('<HTML><body>The employee data included as html.</body></HTML>')


推荐阅读