“ org.springframework.web.HttpMediaTypeNotAcceptableException:找不到可接受的表示形式”以生成xml响应

时间:2019-03-27 03:59:37

标签: java spring-boot spring-restcontroller xml-binding

我尝试从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>

但是仍然抛出相同的异常。我不明白我错过了解决这个问题的方法。

2 个答案:

答案 0 :(得分:1)

consumes批注中设置@GetMapping属性。

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

答案 1 :(得分:0)

(代表问题作者发布)

我修改如下方法:

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

它完美地工作。它返回xml类型的值。