0

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

下面的代码是 RestController.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>

但仍然抛出相同的异常。我无法理解我想解决这个问题的原因。

4

2 回答 2

1

在注释中设置consumes属性。@GetMapping

@GetMapping(value = "getAllUser", produces = MediaType.APPLICATION_XML_VALUE, consumes = MediaType.APPLICATION_XML_VALUE)
于 2019-03-28T02:44:47.007 回答
0

(代表问题作者发布)

我修改方法如下:

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

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

于 2019-04-22T23:02:48.840 回答