MediaType HTML的HttpMediaTypeNotAcceptableException

问题描述 投票:0回答:2

我有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)
java spring spring-boot spring-mvc spring-rest
2个回答
0
投票

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

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

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


0
投票

为了提供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内容,然后使用like:

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

© www.soinside.com 2019 - 2024. All rights reserved.