Spring Boot 媒体类型HTML出现HttpMediaTypeNotAcceptableException异常错误

e37o9pze  于 2022-11-05  发布在  Spring
关注(0)|答案(2)|浏览(423)

我有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内容。然而,当我从浏览器或 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)
kb5ga3dv

kb5ga3dv1#

方法的返回类型是对象Employee。如果需要返回HTML内容,请选择以下任一选项
1.将控制器从@RestController转换为@Controller,添加Spring MVC依赖项,配置模板引擎,创建html并从控制器返回
1.不要从REST控制器返回Employee对象,而是使用Streams将HTML作为Response实体中字节数组发送。

b0zn9rqh

b0zn9rqh2#

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

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

并且springboot将返回名为“employee”的静态html页面。但是在您的示例中,您需要返回一个modelandviewMap,以使动态数据与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>')

相关问题