gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:05:22 33 4
gpt4 key购买 nike

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

关于java - "org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation"生成 xml 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55369590/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com