Sending response before processing in Java servlet - java

I have a Java Servlet application running on JBoss 4 and this application receives POST request from another service. I want to acknowledge back to this service before processing. Is it fine to do the following?
protected void doPost(HttpServletRequest req, HttpServletResponse res) {
readReceivedPOSTData();
//send response
PrintWriter out = res.getWriter();
out.print("ack");
out.close();
//Process
processData(); //takes long time
}
I appreciate your help. Thank you.

The basis is ok.
Just some tips:
Use an identifier in the request so you can check in the future the status of that request.
Start another thread to process the data or use a jms queue
remember that you can't write additional data to the response in the processData() method

Related

Send data in the doPost() response?

I am a complete beginner in web programming. I created an application with Eclipse Java EE and a Tomcat server running in localhost.
The goal of the application is to get information from a client and send back other information.
I developped a servlet and implement a doPost() method that works perfectly. I get information that I saved in a bean named USSDPull and write in a text file named log.txt.
public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException{
USSDPull ussdpull = new USSDPull();
ussdpull.setUssdstring(request.getParameter("ussdstring"));
ussdpull.setSessionid(Integer.parseInt(request.getParameter("sessionid")));
ussdpull.setMsisdn(request.getParameter("msisdn"));
ussdpull.setUssdcode(request.getParameter("ussdcode"));
ussdpull.setEncoding(Integer.parseInt(request.getParameter("encoding")));
response.setContentType("text/text");
response.setCharacterEncoding( "UTF-8" );
PrintWriter out = response.getWriter();
out.flush();
out.println("POST received : " + ussdpull.getUssdstring()+" "+ussdpull.getSessionid()+" "+ussdpull.getMsisdn()+" "+ussdpull.getUssdcode()+" "+ussdpull.getEncoding());
//WRITE IN FILE
FileWriter fw = new FileWriter("D:/Users/Username/Documents/log.txt", true);
BufferedWriter output = new BufferedWriter(fw);
output.write(dateFormat.format(date)+";"+ussdpull.getUssdstring()+";"+ussdpull.getSessionid()+";"+ussdpull.getMsisdn()+";"+ussdpull.getUssdcode()+";"+ussdpull.getEncoding()+"\n");
output.flush();
output.close();
}
I need the servlet to send back 2 specific booleans and 1 string to the client. I don't know how to proceed. Is it possible to use the HttpServletResponse to send the data? Or do I need to find a way to "call" the doGet() method?
The HttpServletResponse itself doesn't give you a way to write data back to the client other than some headers, such as the response code.
However, it has a method called getOutputStream and a method getWriter() that give you resp. an OutputStream or a PrintWriter. You can use these to write data to the response.

App Engine application unable to respond to HttpPost from iOS App

I've set up a Google App Engine application to respond to various HttpPosts and store various bits of information. For some reason in one of my HttpServlets, I am unable to respond back to an HttpPost. I know I've completed this in a similar fashion before but have been unable to figure out the solution neither from trial/attempt nor stackoverflow questions.
Here, my servlet receives the post with no problem:
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
//I do some random processing and storing of data
//Then I respond with a String dependent upon the info I'm given
resp.setContentType("application/JSON");
PrintWriter out = resp.getWriter();
out.print(myResponse);
out.close();
}
I never receive the actual response data back however. The method below is never called. I've set the NSURLConnectionDelegate.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
Does anyone know why this might be?? I'm considering switching to an HttpGet but I know for sure I've done this with an HttpPost before. Any help will be extremely appreciated thanks!

send data from servlet java to jsp

I'm doing a project in java in which I implemented a chat, everything works perfectly only when I receive messages I can not print the web page.
In my Servlet I have a callback method that is invoked when messages arrive, in fact if you see mold them in the console, but if you are sending them to the jsp using the RequestDispatcher can not get them to see.
I would like to know if there is a system that the jsp page listens for a callback method in the servlet?
Obviously, this system should not be constantly invoke the class I have something absurd like that.
So that I can print the messages I receive.
This is my code I put a comment where I should print eventually find in jsp page, or do a redirect by passing parameters post or get
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String strJid = (String) request.getParameter("jid");
String strMessage = (String) request.getParameter("textMessage");
Connection connection = (Connection)getServletContext().getAttribute("classConnection");
ChatManager chatManager = connection.getChatManager();
Chat newChat = chatManager.createChat(strJid, new MessageListener(){
#Override
public void processMessage(Chat chat, Message message){
//from here I have to print the message.getBody () in jsp page,
//how can I do? I'm happy also reload the page and pass as a parameter to get or post
}
});
try{
newChat.sendMessage(strMessage);
}
catch(XMPPException e){
System.out.println("Errore invio messaggio");
}
}
To implement a callback method in your servlet to receive chat messages is the wrong approach. A servlet will be called once for a browser request, creates the HTML page and send it back to the browser. After that there is no such kind of a connection between the servlet and the web page.
In traditional web programming all communication between browser and server is intiated by the client. There is no way for the server to send a message to the client. Workarounds are long polling requests.
But nowadays you can use Websockets. There are several frameworks supporting Websockets both for client and server side. One of them is Atmosphere. Their tutorial is a chat application.

How to drop body of a request after checking headers in Servlet

I want to check the header of the request whether it contains a certain header or not before continuing with the body. For example, I want to check whether a multipart/form-data contains "Authorization" in the header or not. If it is not then there is no need to continue with uploading the multipart body which are generally quite large for file uploading.
Does servlet allow you to do this? I have tried to search on google randomly but there is no luck. Here is the code i try in my servlet but it still continues with recieving the body before this doPost method is called. It seems that the stream is fully received before the servlet is invoked.
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
if (request.getHeader("Authorization") == null) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
out.println("Status: " + HttpServletResponse.SC_UNAUTHORIZED + " - UNAUTHORIZED");
return;
}
// ... the rests
}
That's the limitation of HTTP. You can't send a response when the request hasn't been read fully to end.
RFC 2616 says:
An HTTP/1.1 (or later) client sending a message-body SHOULD monitor the network connection for an error status while it is transmitting the request. If the client sees an error status, it SHOULD immediately cease transmitting the body.
So I disagree, this is not a HTTP limitation but a servlet one.

How to make a servlet interact with the API of a website and also store the XML response?

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String text = "some text";
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write(text); // Write response body.
}
If I use this servlet , where request variable will have the url of the API of the website . Then how do I capture the response ? I would want to know what is the code to do that , and is this the right way to go about it when trying to build a JSP page that deals with interacting with an API of a website and showing data ?
You're confusing things. The HttpServletRequest is the HTTP request which the client (the webbrowser) has made to reach the servlet. The HttpServletResponse is the response which you should use to send back the result to the client (the webbrowser).
If you want to fire a HTTP request programmatically, you should use java.net.URLConnection.
URLConnection connection = new URL("http://example.com").openConnection();
InputStream input = connection.getInputStream(); // This contains the response. You need to convert this to String or some bean and then display in JSP.
See also:
How to use java.net.URLConnection to fire and handle HTTP requests

Categories

Resources