英文:
REST API Response.ok(entity).build() doesn't show text
问题
以下是翻译好的部分:
我正在为一个学校练习创建一个简单的Restful API,但是遇到了一个问题。当我尝试在网页上显示实体列表或者只是单个实体时,页面上没有显示任何文本。它似乎能够找到正确的实体(当我进行筛选时,它会显示正确数量的实体),只是没有显示文本。也许它没有运行ToString方法?但我在我的ToString方法中没有发现任何错误。
以下是一个示例:
在我的UserResources中返回用户的函数:
@GET //GET请求位于http://localhost:XXXX/users/1
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getUserPath(@PathParam("id") int Id) {
User user = fakeDatabase.getUser(Id);
if (user == null) {
return Response.status(Response.Status.BAD_REQUEST).entity("请提供有效的用户ID。").build();
} else {
return Response.ok(user).build();
}
}
在FakeDatabase中的getUser函数:
public User getUser(int userId) {
for (User user : userList) {
if (user.GetUserId() == userId) {
return user;
}
}
return null;
}
User类的ToString方法:
@Override
public String toString() {
String WishlistItems = "";
for(String item : Wishlist){
WishlistItems = WishlistItems + item + ", ";
}
return "User (" + UserId + ") {" + "\n" +
"Email Address = " + EmailAddress + "\n" +
"UserName = " + UserName + "\n" +
Platform.toString() + " ID = " + PlatformID + "\n" +
"Wishlist :" + WishlistItems + "\n" +
"}" + "\n";
}
我在网站上得到的结果:
有人知道这个问题的解决方案吗?
编辑:完整的User类(我也更新了ToString方法):
@XmlRootElement
public class User {
private int UserId;
private String UserName;
private String EmailAddress;
private int PasswordHash;
private Platform Platform;
private String PlatformID;
private ArrayList<String> Wishlist = new ArrayList<String>();
public User(int userId, String Password, String emailAddress, String userName, Platform platform, String platformID){
UserId = userId;
EmailAddress = emailAddress;
UserName = userName;
Platform = platform;
PlatformID = platformID;
hashPassword(Password);
}
public User(){
}
public int GetUserId(){
return UserId;
}
public String GetUserName(){
return UserName;
}
public void SetUserName(String UserName){
this.UserName = UserName;
}
public String GetEmailAddress(){
return EmailAddress;
}
public void SetEmailAddress(String EmailAddress){
this.EmailAddress = EmailAddress;
}
public Platform GetPlatform(){
return Platform;
}
public void SetPlatform(Platform Platform){
this.Platform = Platform;
}
public String GetPlatformID(){
return PlatformID;
}
public void SetPlatformID(String PlatformID){
this.PlatformID = PlatformID;
}
public void AddToWishlist(String item){
Wishlist.add(item);
}
public ArrayList<String> GetWishlist(){
return Wishlist;
}
public void SetWishlist(ArrayList<String> Wishlist){
this.Wishlist = Wishlist;
}
public void hashPassword(String Password) {
PasswordHash = Objects.hash(Password);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return UserId == user.GetUserId();
}
@Override
public String toString() {
String WishlistItems = "";
for(String item : Wishlist){
WishlistItems = WishlistItems + item + ", ";
}
return "User (" + UserId + ") {" + "\n" +
"Email Address = " + EmailAddress + "\n" +
"UserName = " + UserName + "\n" +
Platform.toString() + " ID = " + PlatformID + "\n" +
"Wishlist :" + WishlistItems + "\n" +
"}" + "\n";
}
}
<details>
<summary>英文:</summary>
I am creating a simple Restful API for a school exercise but I'm running into a problem. When I try to show a list of entities, or just a single entity on the webpage it doesn't show any text. It does seem to find the right entities (when I filter, it shows the correct number of entities), it just doesn't show the text. Maybe it doesn't run the ToString? But I don't see anything wrong in my ToString method.
Here's an example:
Function to return a user in my UserResources:
@GET //GET at http://localhost:XXXX/users/1
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getUserPath(@PathParam("id") int Id) {
User user = fakeDatabase.getUser(Id);
if (user == null) {
return Response.status(Response.Status.BAD_REQUEST).entity("Please provide a valid user ID.").build();
} else {
return Response.ok(user).build();
}
}
getUser in FakeDatabase:
public User getUser(int userId) {
for (User user : userList) {
if (user.GetUserId() == userId) {
return user;
}
}
return null;
}
User ToString:
@Override
public String toString() {
String WishlistItems = "";
for(String item : Wishlist){
WishlistItems = WishlistItems + item + ", ";
}
return "User (" + UserId + ") {" + "\n" +
"Email Address = " + EmailAddress + "\n" +
"UserName = " + UserName + "\n" +
Platform.toString() + " ID = " + PlatformID + "\n" +
"Wishlist :" + WishlistItems + "\n" +
"}" + "\n";
}
The result I get on the website:
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/zLOB8.png
Anyone know a solution to this problem?
EDIT: The full user class (also I updated the toString method):
@XmlRootElement
public class User {
private int UserId;
private String UserName;
private String EmailAddress;
private int PasswordHash;
private Platform Platform;
private String PlatformID;
private ArrayList<String> Wishlist = new ArrayList<String>();
public User(int userId, String Password, String emailAddress, String userName, Platform platform, String platformID){
UserId = userId;
EmailAddress = emailAddress;
UserName = userName;
Platform = platform;
PlatformID = platformID;
hashPassword(Password);
}
public User(){
}
public int GetUserId(){
return UserId;
}
public String GetUserName(){
return UserName;
}
public void SetUserName(String UserName){
this.UserName = UserName;
}
public String GetEmailAddress(){
return EmailAddress;
}
public void SetEmailAddress(String EmailAddress){
this.EmailAddress = EmailAddress;
}
public Platform GetPlatform(){
return Platform;
}
public void SetPlatform(Platform Platform){
this.Platform = Platform;
}
public String GetPlatformID(){
return PlatformID;
}
public void SetPlatformID(String PlatformID){
this.PlatformID = PlatformID;
}
public void AddToWishlist(String item){
Wishlist.add(item);
}
public ArrayList<String> GetWishlist(){
return Wishlist;
}
public void SetWishlist(ArrayList<String> Wishlist){
this.Wishlist = Wishlist;
}
public void hashPassword(String Password) {
PasswordHash = Objects.hash(Password);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return UserId == user.GetUserId();
}
@Override
public String toString() {
String WishlistItems = "";
for(String item : Wishlist){
WishlistItems = WishlistItems + item + ", ";
}
return "User (" + UserId + ") {" + "\n" +
"Email Address = " + EmailAddress + "\n" +
"UserName = " + UserName + "\n" +
Platform.toString() + " ID = " + PlatformID + "\n" +
"Wishlist :" + WishlistItems + "\n" +
"}" + "\n";
}
}
</details>
# 答案1
**得分**: 0
你在问题中标记了Spring Boot,但是Spring Boot的代码看起来有些不同。试试类似这样的代码:
```java
@GetMapping("/users/{id}")
public ResponseEntity<User> getUserPath(@PathVariable("id") int Id) {
User user = fakeDatabase.getUser(Id);
if (user == null) {
return ResponseEntity.badRequest().body("Please provide a valid user ID.");
} else {
return ResponseEntity.ok(user);
}
}
英文:
You tagged your question with Spring Boot, but Spring Boot code does look different. Try it with something like that:
@GetMapping("/users/{id}")
public ResponseEntity<User> getUserPath(@PathVariable("id") int Id) {
User user = fakeDatabase.getUser(Id);
if (user == null) {
return ResponseEntity.badRequest().body("Please provide a valid user ID.");
} else {
return ResponseEntity.ok(user);
}
}
答案2
得分: 0
响应实体未通过toString()
方法序列化。如果您想要返回一个字符串,那么您必须通过调用user.toString()
来设置字符串实体。如果您将一个对象设置为实体,它将被视为POJO。这意味着您必须为您的属性定义适当的setXXX/getXXX
方法。您的User
类使用了错误的大小写。
请参阅在JAX-RS中设置响应体以获取更多详细信息(尤其是第3.4节,可能对您有帮助的JSON响应使用POJO部分)。
英文:
The response entity is not serialized via the toString()
mehtod. If you want to return a string then you have to set a string entity by calling user.toString()
yourself.
If you set an object as entity it will be treated as an POJO. This means you have to define appropriate setXXX/getXXX methods for your attributes. Your User
class uses the wrong case.
Have a look at Set a Response Body in JAX-RS for more details (Especially section 3.4. JSON Response Using POJO may be in your interest)
答案3
得分: 0
这里是一个示例:
这里是一个示例:
@RestController
@RequestMapping("/user")
public class UserController {
@GET // 在 http://localhost:XXXX/users/1 发起 GET 请求
@Path("/{id}")
@Produces(MediaType.APPLICATION_XML)
public Response<User> getUserPath(@PathParam("id") int Id) {
return fakeDatabase.getUser(Id).ifPresentOrElse(u -> Response.ok(u), return Response.empty());
}
}
public class FakeBase {
public Optional<User> getUser(int userId) {
return userList.stream().filter(u -> u.hasId(userId)).findFirst();
}
}
public class User {
public boolean hasId(int id) {
return this.id == id;
}
}
User.toString() 是无用的。
英文:
Here is an purpose :
@RestController
@RequestMapping("/user")
public class UserController {
@GET //GET at http://localhost:XXXX/users/1
@Path("/{id}")
@Produces(MediaType.APPLICATION_XML)
public Response<User> getUserPath(@PathParam("id") int Id) {
return fakeDatabase.getUser(Id).ifPresentOrElse(u -> Response.ok(u), return Response.empty());
}
}
public class FakeBase {
public Optional<User> getUser(int userId) {
return userList.stream().filter(u -> u.hasId(userId)).findFirst();
}
}
public class User () {
public boolean hasId(int id) {
return this.id == id;
}
}
User.toString()
is useless.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论