0

I try to produce xml-format data from spring boot restcontroller. Below is User model codes first.

@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;
}

And Below codes are 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 format data are successfully returned. But xml-format values are not generated. It throws the following exception.

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

I add the a few dependencies into pom.xml like below,

<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>

But still throws the same exception. I can not understand what I miss to solve this issue.

halfer
  • 18,701
  • 13
  • 79
  • 158
Joseph Hwang
  • 991
  • 1
  • 22
  • 45

2 Answers2

1

Set the consumes attribute in your @GetMapping annotation.

@GetMapping(value = "getAllUser", produces = MediaType.APPLICATION_XML_VALUE, consumes = MediaType.APPLICATION_XML_VALUE)
k9yosh
  • 781
  • 1
  • 10
  • 27
0

(Posted on behalf of the question author).

I modify the method like below:

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

It work perfectly. It return xml-type values.

halfer
  • 18,701
  • 13
  • 79
  • 158