2
我有我的Restful web服務在java和mongodb上的問題。RestFul java與mongodb如何添加@QueryParam
這裏是我的類
public JSONArray returnAll() throws Exception{
MongoClient mongoClient = mongoConnection();
DBCollection collection = mongoClient.getDB("mydb").getCollection("zip");
BasicDBObject query = new BasicDBObject();
query.put("city","CHICOPEE");
DBCursor cursor = collection.find(query);
JSON json = new JSON();
String serialize = json.serialize(cursor);
JSONArray AllJson = new JSONArray(serialize);
return AllJson;
}
,這是我的WebService類
@Path("/All")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response returnDatabaseAll() throws Exception{
String returnString = null;
JSONArray json = new JSONArray();
try{
greatontimeSchema dao = new greatontimeSchema();
json = dao.returnAll();
returnString = json.toString();
}catch (SQLException ex){
ex.printStackTrace();
return Response.status(500).entity("Server was not able").build();
}catch(Exception e){
e.printStackTrace();
return Response.status(500).entity("Server was not able").build();
}
return Response.ok(json).build();
}
這是爲我工作。它是這樣返回正確的JSON數據。當我打電話
http://192.168.1.5:8080/com.projecttest.JSMongo/api/mongoWS/All
[{ 「_id」: 「01013」, 「城市」: 「CHICOPEE」, 「祿」: - 72.607962,42.162046], 「啪」:23396, 「狀態」: 「MA」},{「_ id」:「01020」,「city」:「CHICOPEE」,「loc」:[ - 72.576142,42.176443],「pop」:31495,「state」:「MA」}]
但是,如果我想@QueryParam添加到我的班這樣
public JSONArray returnAll (String city) throws Exception{
MongoClient mongoClient = mongoConnection();
DBCollection collection = mongoClient.getDB("mydb").getCollection("zip");
BasicDBObject query = new BasicDBObject();
query.put("city",city);
DBCursor cursor = collection.find(query);
JSON json = new JSON();
String serialize = json.serialize(cursor);
JSONArray AllJson = new JSONArray(serialize);
return AllJson;
}
並改變我的web服務類這
@Path("{city}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response returnDatabaseAll(@QueryParam("city") String city) throws Exception{
String returnString = null;
JSONArray json = new JSONArray();
try{
greatontimeSchema dao = new greatontimeSchema();
json = dao.returnAll(city);
returnString = json.toString();
}catch (SQLException ex){
ex.printStackTrace();
return Response.status(500).entity("Server was not able").build();
}catch(Exception e){
e.printStackTrace();
return Response.status(500).entity("Server was not able").build();
}
return Response.ok(json).build();
}
當我輸入網址這樣
http://192.168.1.5:8080/com.projecttest.JSMongo/api/mongoWS/CHICOPEE
它返回
[]
我在java的新手。我試圖Google,但我找不到我的解決方案。 在這種情況下,我用MYSQL數據庫開發它沒有問題。 但與MongoDB我真的不知道。 任何人都可以幫我嗎?對不起,我英文很差。
使用'@ PathParam',你有'@ QueryParam'。 –
太棒了!是工作 !!非常感謝。 @DaveMorrissey – greatontime