通过 Jersey 的 JAX-RS -> HTTP 正文中没有返回内容(方法完成没有错误)
JAX-RS via Jersey -> No Content Returned In HTTP Body (Method Completes Without Errors)
我正在通过 Jersey 使用 JAX-RS,我遇到了 "bump in the road"。我有一个方法应该 return HTTP POST 之后的 JSON 对象。它确实执行成功,但没有 return JSON 对象(除非我做一个变通)。我希望有人能告诉我为什么这不能像我期望的那样工作。见以下代码:
@Path("chatroom")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class ChatroomResource {
ChatroomService service = new ChatroomService();
//this works properly and returns the object as json
@GET
public List<Chatroom> getChatrooms() {
return service.getChatrooms();
}
/**********
* This works, but does not return any content in response body
*******/
@POST
public Chatroom addRoom(Chatroom room) {
return service.addChatroom(room);
/*
* This one does produce content body
* service.addChatroom(room);
* return room;
*/
}
}
以下方法在服务对象中:
public Chatroom addChatroom(Chatroom room) {
return Cache.getChatrooms().put(room.getRoomName(), room);
}
可能出了什么问题以及如何解决
根据您提供的 肤浅的 详细信息,我相信以下指令会返回 null
:
return Cache.getChatrooms().put(room.getRoomName(), room);
在 put(String, Chatroom)
方法中,我猜你正在将 Chatroom
实例添加到缓存中,但你返回的是 null
而不是 Chatroom
实例。
以下应该有效:
public Chatroom addChatroom(Chatroom room) {
Cache.getChatrooms().put(room.getRoomName(), room);
return room;
}
更新 1
正如您在评论中提到的,您正在使用 Hashtable
来实现缓存。
注意 put(K, V)
method returns the previous value of the specified key in the hashtable, or null
if it did not have one. For more details, consider reading the documentation.
更新 2
您是否考虑过使用 HashMap
而不是 Hashtable
?
如果同步成为问题,您可能会对 ConcurrentHashMap
.
感兴趣
我正在通过 Jersey 使用 JAX-RS,我遇到了 "bump in the road"。我有一个方法应该 return HTTP POST 之后的 JSON 对象。它确实执行成功,但没有 return JSON 对象(除非我做一个变通)。我希望有人能告诉我为什么这不能像我期望的那样工作。见以下代码:
@Path("chatroom")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class ChatroomResource {
ChatroomService service = new ChatroomService();
//this works properly and returns the object as json
@GET
public List<Chatroom> getChatrooms() {
return service.getChatrooms();
}
/**********
* This works, but does not return any content in response body
*******/
@POST
public Chatroom addRoom(Chatroom room) {
return service.addChatroom(room);
/*
* This one does produce content body
* service.addChatroom(room);
* return room;
*/
}
}
以下方法在服务对象中:
public Chatroom addChatroom(Chatroom room) {
return Cache.getChatrooms().put(room.getRoomName(), room);
}
可能出了什么问题以及如何解决
根据您提供的 肤浅的 详细信息,我相信以下指令会返回 null
:
return Cache.getChatrooms().put(room.getRoomName(), room);
在 put(String, Chatroom)
方法中,我猜你正在将 Chatroom
实例添加到缓存中,但你返回的是 null
而不是 Chatroom
实例。
以下应该有效:
public Chatroom addChatroom(Chatroom room) {
Cache.getChatrooms().put(room.getRoomName(), room);
return room;
}
更新 1
正如您在评论中提到的,您正在使用 Hashtable
来实现缓存。
注意 put(K, V)
method returns the previous value of the specified key in the hashtable, or null
if it did not have one. For more details, consider reading the documentation.
更新 2
您是否考虑过使用 HashMap
而不是 Hashtable
?
如果同步成为问题,您可能会对 ConcurrentHashMap
.