我尝试从 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>
但仍然抛出相同的异常。我无法理解我想解决这个问题的原因。