I have got a Simple JERSEY WEBService which is responsible to return states present in our Database
package com.services.regg;
@Path("/getstates")
public class FetchStates {
@GET
@Consumes("application/text")
@Produces("application/json")
public String getAllSates() throws JSONException
{
JSONArray jsonarray_allstates = new JSONArray();
Connection dbConnection = null;
PreparedStatement getAllStatesPst = null ;
ResultSet getAllStatesResltSet = null;
try
{
dbConnection = DBConnectionOrient.getDBConnection();
getAllStatesPst = dbConnection.prepareStatement("select stateID , stateName from tbl_state ORDER BY stateName");
getAllStatesResltSet = getAllStatesPst.executeQuery();
while(getAllStatesResltSet.next())
{
JSONObject eachrecordjsonObj = new JSONObject();
String stateID = getAllStatesResltSet.getString("stateID").trim();
String stateName = getAllStatesResltSet.getString("stateName").trim();
eachrecordjsonObj.put("stateID", stateID).put("stateName", stateName);
if(!stateName.isEmpty() && !stateName.equals(""))
{
jsonarray_allstates.put(eachrecordjsonObj);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
DBConnectionOrient.close(getAllStatesPst,getAllStatesResltSet);
DBConnectionOrient.close(dbConnection);
}
String response = "jsonCallback("+jsonarray_allstates.toString()+")";
return response;
}
}
All this works fine .
As this works for a Mobile Application , we are seeing very slow responses from backend
I want to optimize the performance of the Application from my Side . For this I have seen Jersey Cache Control .
CacheControl cc = new CacheControl();
cc.setMaxAge(86400);
cc.setPrivate(true);
ResponseBuilder builder = Response.ok(myBook);
builder.cacheControl(cc);
return builder.build();
My question is , is it possible to use CacheControl
in my code as I am directly sending String instead of ResponseBuilder
.
If so , could you please let me know , how to modify my code to use Cache Control ?
Just restructure your code to return Response
instead of String
. Where Response.ok(myBook);
is used, just pass it your jsonp response
in instead of myBook
.
The only other ways involve manipulating the headers directly.
If you MUST stick to using the String
return type, then you can inject the HttpSerlvetResponse
and just set the header
@GET
public String getAllSates(@Context HttpServletResponse response) {
CacheControl cc = new CacheControl();
cc.setMaxAge(86400);
cc.setPrivate(true);
response.addHeader("Cache-Control", cc.toString());
[...]
}
Or you can add the header inside a ContainerResponseFilter
, if you don't want to have to add it in every method. Not sure which Jersey version you're using, but with Jersey 2.x, you can determine which method will use the filter, so that only chosen resources will go through this filter. Not sure about Jersey 1.x, if this feature is available. Here is the documentation for 2.x.