"org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation" 产生 xml 响应

"org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation" to produce xml response

我尝试从 spring boot restcontroller 生成 xml 格式的数据。下面首先是用户模型代码。

@Entity  
@Table(name="BlogUser")
@XmlRootElement
public class User {

  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  @Column(name="USER_ID", nullable = false, unique = true)
  private Long id;

  @Column(unique=true, nullable=false)
  @Length(min=2, max=30)
  @NotEmpty
  private String username;

  @Column(nullable=false)
  @Length(min=5)
  @NotEmpty
  private String password;

  @Column
  @Email
  @NotEmpty
  private String email;

  @Column
  @NotEmpty
  private String fullname;

  @Column
  private UserRole role;
}

下面的代码是RestConstroller.java

@RestController
@RequestMapping(value="/rest/user")
@SessionAttributes("user")
public class UserRestController {
  @Autowired
  private UserService userService;

  @GetMapping(value="getAllUser", produces=MediaType.APPLICATION_XML_VALUE)
  public ResponseEntity<List<User>> getAllPost() {
    List<User> users = this.userService.findAll();

    if(users == null || users.isEmpty())
      return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
      return new ResponseEntity<List<User>>(users, HttpStatus.OK);
    }
  }
}

Json格式数据返回成功。但不会生成 xml 格式的值。它抛出以下异常。

.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]

我将一些依赖项添加到 pom.xml 中,如下所示,

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

但还是抛出同样的异常。我不明白我想解决这个问题。

@GetMapping 注释中设置 consumes 属性。

@GetMapping(value = "getAllUser", produces = MediaType.APPLICATION_XML_VALUE, consumes = MediaType.APPLICATION_XML_VALUE)

(代题作者发表).

我修改如下方法:

@GetMapping(value="getAllUser", produces = { "application/xml", "text/xml" }, consumes = MediaType.ALL_VALUE)
    public ResponseEntity<List<User>> getAllPost() {
..

它工作得很好。它 return xml 类型值。