有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

MediaType HTML的java HttpMediaTypeNotAcceptableException

我有弹簧休息控制器,如下所示:

@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)

共 (2) 个答案

  1. # 1 楼答案

    为了提供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>')

  2. # 2 楼答案

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

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

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