How can I recover the value after recovering control in a servlet? - java

I am trying to include several servlets in the main servlet to get finish some processs and retrieve values. In this example, I am receiving the control from a jsp file to the main servlet. After this servlet send call to the next servlet to carry out an operation related to a Java List and after returns the control to the main servlet. However, I am not able to recover the value of this List. How can I recover values from servlets that I am calling from the main servlet? The part of source code is the next:
(Main Servlet)
DeletePolicy.java:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter printWriter = response.getWriter();
Client client= Client.create();
WebResource webResource= client.resource("http://localhost:8080/clientLibrary/webapi/policy");
//create an object of RequestDispatcher
RequestDispatcher rd = request.getRequestDispatcher("GetPolicy");
// send the client data available with req of delete to req of getPolicy with include()
rd.include(request, response);
// To receive the parameter from the second servlet
List<Policy> policies = (List<Policy>) request.getAttribute("policies");
printWriter.print("List of books in Delete: ");
for(Policy policy : policies) {
printWriter.println("<li>"+"ID: "+policy.getId()+"<br>"+"Max Number of Books: "+policy.getMax_books()+"<br>"+"Year of Book: "+policy.getYear_book()+"<br>"+"Activated: "+policy.getActivate()+"<br></li><br>");
}
printWriter.print("I am comming back in Delete to send a request to Delete method");
/*ClientResponse rs=webResource.accept(
MediaType.APPLICATION_JSON_TYPE,
MediaType.APPLICATION_XML_TYPE).
delete(ClientResponse.class,input);
printWriter.print("Delete a policy");*/
}
/* Include solution provided by Jozef Chocholacek: request.setAttribute("policies", policies);
GetPolicy.java(Second Servlet):
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter printWriter = response.getWriter();
Client client= Client.create();
WebResource webResource= client.resource("http://localhost:8080/clientLibrary/webapi/policy");
printWriter.println("<u>Searching for current policies...</u><br>");
ClientResponse rs=webResource.accept(
MediaType.APPLICATION_JSON_TYPE,
MediaType.APPLICATION_XML_TYPE).
get(ClientResponse.class);
//ClientResponse rs = webResource.type(MediaType.APPLICATION_JSON).delete(ClientResponse.class,input);
/*Transform json to java object*/
String jsonPolicy=rs.getEntity(String.class);
Gson gson = new Gson();
Policy[] PolicyA = gson.fromJson(jsonPolicy, Policy[].class);
List<Policy> policies = Arrays.asList(PolicyA);
for(Policy policy : policies) {
System.out.println(policy.getId()+" "+policy.getMax_books()+", "+policy.getYear_book()+", "+policy.getActivate()+", ");
}
//Send List to the servlet that is calling
request.setAttribute("policies", policies);
/*Display book list in the servlet*/
printWriter.println("<h1>List of Policies</h1>");
if (policies.isEmpty()){
printWriter.println("<html><body>Sorry, we did not have any policy"+"<br>");
}else{
printWriter.println("<html><body>The complete list of policies: <br>");
printWriter.println("<ul>");
for(Policy policy : policies) {
printWriter.println("<li>"+"ID: "+policy.getId()+"<br>"+"Max Number of Books: "+policy.getMax_books()+"<br>"+"Year of Book: "+policy.getYear_book()+"<br>"+"Activated: "+policy.getActivate()+"<br></li><br>");
}
}
printWriter.println("</body></html>");
}
Thank you in advance
Cheers

Well, in your first servlet (DeletePolicy.java) you use
List<Policy> policies = (List<Policy>) request.getAttribute("policies");
but the second servlet (GetPolicies.java) does not store this list into request. You have to add
request.setAttribute("policies", policies);
into your second servlet.

Related

Does a HttpServlet have to respond to a request?

I have several servlets that do things server side. On a few I just encode some unnecessary data and send it back, which seems pointless. Do you have to respond ? What happens when you just say return ? I've done that before and nothing seems to go wrong but I am relatively new to servlets. Are there consequences for simply returning that go above my head ? And what exactly happens when you return;
if(request.getParameter("name").equals("saveusedcards")) {
String sessId = request.getSession().getId();
//encode request with confirmation that cards were successfully updated
if(usersUpdatedCards.get(sessId).isEmpty()){
//no cards were seen
}
boolean success = DataDAO.updateCards(usersUpdatedCards.get(sessId));
if(success){
System.out.println("Data base update successfull!");
String responseMessage = new Gson().toJson("card successfully udpated");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
System.out.println("updated cards response message: "+responseMessage);
response.getWriter().write(responseMessage);
return;
} else {
System.out.println("Data base update failed...");
String responseMessage = new Gson().toJson("card was not successfully updated");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
System.out.println("updated cards response message: "+responseMessage);
response.getWriter().write(responseMessage);
return;
}
}
The servlet must produce an HTTP response for the client, however it is perfectly acceptable to return no content in the response body. When doing so your servlet should make this clear to the client by sending a response code of 204 (no content). Reference: https://httpstatuses.com/204
Here is an example of how you would set the response code from the doGet method. You could do the same from doPost or service methods.
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// Do whatever work you need to do here...
res.setStatus(HttpServletResponse. SC_NO_CONTENT); // This returns a 204
}

Program hanging at call for REST service

I am running a REST service on Tomcat and a client service from Eclipse.
My program keeps stopping when on it's second run through. I am not receiving any exceptions in the console running Tomcat
The first time my Controller is called, there is no issue and everything runs fine. After everything executes in the Controller, the user is redirected back to a JSP page. When a button is clicked on the JSP page, the Controller code shown below is run again.
However this time, the program stops in the function:
getOrderDetails(id, order, service);
while executing the line:
String orderXML = service.path("rest").path("coffee").header("user", "customer-123").accept(MediaType.APPLICATION_XML_TYPE).get(String.class);
This line calls the REST service which will interact with my SQLite database and then return some `XML.
I really cannot work out why it is stopping on the second attempt!
Any help with this would be GREATLY appreciated!
Thank you!
Update 1: If it's of any significance, I find that when the program hangs, I need to not only quit Eclipse and restart it, but I also need to restart the server. Otherwise, the client program won't work properly.
Update 2: I have defined only one ClientResponse to be used at all points in the program.
Update 3: I've been using ClientResponse.close() after each of my requests.
NOTE: Code updated to reflect comment below
Controller:
static ClientConfig config = new DefaultClientConfig();
static Client client = Client.create(config);
static WebResource service = client.resource(getBaseURI());
ClientResponse clientResp;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Get All Coffee Orders
clientResp = service.path("rest").path("coffee").header("user", "customer-123").type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).get(ClientResponse.class);
String orderXML = clientResp.getEntity(String.class);
clientResp.close();
try {
Document document = loadXMLFromString(orderXML);
NodeList nodeList = document.getDocumentElement().getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element elem = (Element) node;
CoffeeOrder order = new CoffeeOrder();
// Set ID
String id = elem.getElementsByTagName("id").item(0).getChildNodes().item(0).getNodeValue();
order.setId(id);
// Get ALL Order Details
getOrderDetails(id, order);
// Get ALL Payment Details
getPaymentDetails(id, order);
// If order has not been cancelled, add to open orders
if (!order.getOrderStatus().equals("cancelled")){
openOrders.add(order);
// If order has been cancelled, add to cancelled orders.
} else {
cancelledOrders.add(order);
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response);
}
// Get all Order Details
private void getOrderDetails(String id, CoffeeOrder order){
// PROGRAM STOPS HERE ON SECOND RUN THROUGH
clientResp = service.path("rest").path("coffee").path(id).header("user", "customer-123").type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).get(ClientResponse.class);
orderXML = clientResp.getEntity(String.class);
clientResp.close();
// Do Things here with XML
} catch (Exception e){
e.printStackTrace();
}
}
// Get all Payment Details
private void getPaymentDetails(String id, CoffeeOrder order){
clientResp = service.path("rest").path("payment").path(id).header("user", "customer-123").type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).get(ClientResponse.class);
orderXML = clientResp.getEntity(String.class);
clientResp.close();
// Do Things here with XML
} catch (Exception e){
e.printStackTrace();
}
}
I finally realised what the problem was...
It had to do with multiple database connections that were being opened on the server side! This was causing the issue and once I dealt with that the problem resolved itself.
Thanks for all your help!

Jsp that calls a web service in domain

I want to write a .jsp (tomcat5.5) that calls a web service (IIS in domain). I get an HTTP Error 401 Unauthorized. It seems that in order to call the web service you have to be a domain user. I want to allow access to the jsp only to domain users. The request.getRemoteUser() in the jsp returns null but not the domain user that calls the jsp.
From a web browser I call the web service and it works fine.
I am a bit confused with this. Can someone tell me how can the issue be resolved?
Do i have to make tomcat make SSO?
Thank you for your time.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter o = response.getWriter();
o.println("sstarting...");
o.println("user.name ".concat(System.getProperty("user.name")));
o.println("request.getRemoteUser() ".concat(request.getRemoteUser()));
try {
GetUserRoles getUserRolesRequest = new GetUserRoles();
getUserRolesRequest.setApplicationId(121);
getUserRolesRequest.setUserName("user");
GetUserRolesResponse getUserRolesResponse;
ServiceStub stub =new ServiceStub() ;
stub._getServiceClient().getOptions().setProperty(HTTPConstants.CHUNKED,"false");
getUserRolesResponse = stub.getUserRoles(getUserRolesRequest); //IT FAILS HERE 401
String str =getUserRolesResponse.getGetUserRolesResult().toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
o.println(e.getMessage());
}
}

Return from doPost() in JSP

I am trying to implement REST type architecture without using any framework. So I am basically calling a JSP from my client end which is doing a doPost() on to the remote server providing services. Now I am able to pass the data from client to server in JSON format but I don know how to read the response. Can someone help me out with this.
Client Side:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
....
....
HttpPost httpPost = new HttpPost("http://localhost:8080/test/Login");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
//Send post it as a "json_message" paramter.
postParameters.add(new BasicNameValuePair("json_message", jsonStringUserLogin));
httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse fidresponse = client.execute(httpPost);
....
....
}
Server Side:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String jsonStringUserLogin = (String)request.getParameter("json_message");
....
....
request.setAttribute("LoginResponse", "hello");
// Here I need to send some string back to the servlet which called. I am assuming
// that multiple clients will be calling this service and do not want to use
// RequestDispatcher as I need to specify the path of the servlet.
// I am looking for more like return method which I can access through
// "HttpResponse" object in the client.
}
I just started with servlets and wanted to implement a REST service by myself. If you have any other suggestion please do share... Thank You,
in doPost you simply have to do :
response.setContentType("application/json; charset=UTF-8;");
out.println("{\"key\": \"value\"}"); // json type format {"key":"value"}
and this will return json data to client or servlet..
reading returned data using jquery ajax ...
on client side using jquery do the following :
$.getJSON("your servlet address", function(data) {
var items = [];
var keys= [];
$.each(data, function(key, val) {
keys.push(key);
items.push(val);
});
alert(keys[0]+" : "+items[0]);
});
on servlet you know how to read json data
After you executed the post you can ready the response like this.
HttpEntity entity = fidresponse.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
String l = null;
String rest = "";
while ((l=br.readLine())!=null) {
rest=rest+l;
}
Here rest will contain your json response string.
You can also use StringBuffer.

response.sendRedirect() in Servlet not working correctly after file upload

I have a web application with a simple upload function. The idea is to allow user select a file and upon successfully upload, redirect to index.jsp.
However, although the file got uploaded, the response.redirect is not working. After a successfully upload, the page doesn't get redirected. It just stays there. The weird thing is that I can see it is processing the index.jsp from the tomcat server log even though it doesn;t get redirected.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
boolean status=false;
if (!ServletFileUpload.isMultipartContent(request)) {
throw new IllegalArgumentException("Request is not multipart, please 'multipart/form-data' enctype for your form.");
}
ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
PrintWriter writer = response.getWriter();
response.setContentType("text/plain");
try {
List<FileItem> items = uploadHandler.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
File file = new File(getServletContext().getRealPath("/WEB-INF/upload"), item.getName());
item.write(file);
writer.write("{\"name\":\"" + item.getName() + "\",\"type\":\"" + item.getContentType() + "\",\"size\":\"" + item.getSize() + "\"}");
}
}
//redirect to index.jsp if successfully
redirect(request, response);
} catch (FileUploadException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
writer.close();
}
}
The redirect method:
private void redirect(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
The file upload plugin is from https://aquantum-demo.appspot.com/file-upload
I used the front-end and developed the upload event handler using java apache fileupload. Everything works fine except the redirect part.
The application.js file which handles the JSON returns:
$(function () {
// Initialize jQuery File Upload (Extended User Interface Version):
$('#file_upload').fileUploadUIX();
// Load existing files:
$.getJSON($('#file_upload').fileUploadUIX('option', 'url'), function (files) {
var options = $('#file_upload').fileUploadUIX('option');
options.adjustMaxNumberOfFiles(-files.length);
$.each(files, function (index, file) {
options.buildDownloadRow(file, options)
.appendTo(options.downloadTable).fadeIn();
});
});
});
Any ideas?
You're attempting to send two responses on a single request. One with JSON data in the response body and one which redirects the response to another request. This is not going to work. You can send only one response back per request. A redirect requires an untouched (uncommitted) response body, otherwise the redirect will just fail with IllegalStateException: response already committed in the server logs.
You need to move the redirect call from the servlet code to JavaScript code. Get rid of the redirect() line in the servlet and add the following line as the last line of the $.getJSON() callback function.
window.location = '/index.jsp';
This way JavaScript will take care of the redirect.

Categories

Resources