tags:

views:

69

answers:

3

hi, I have the following problem. I programmed a java servlet, which responses to ajax requests from my javascript application. the answer from the java servlet is a xml encoded message. normally everything works well, but if I send "too much" (I think) Ajax reqeusts, it happens that more responses are within one ajax reponse, and as a consequence, firefox complains with the error message "junk after root document": e.g.:

<root>
 <node1></node1>
</root>

<root>
 <node1></node1>
</root>

and that is not allowed (two times <root> in one message). Why does this happen? I always thought for each ajax call, a new servlet instance will be started. is that wrong?

+1  A: 

Servlet instances are managed by container and we cannot assume which instance would be managing the incoming ajax call. So if you are using instance variables then this could cause an issue. So you cannot assume, that one servlet instance is managing one request only.

If you could post the servlet code, the exact error can be looked up.

techzen
A: 

hi I'm currently using tomcat as server. my servlet code looks like the following:

public class ServletTest extends HttpServlet 
{ 
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    {
      String response = "\r\n<root>";

      // format response
      res.setContentType("text/xml");
      res.setHeader("Cache-Control", "no-cache");

      // get writer object
      try
      {
        writer = res.getWriter();
      }catch(IOException e)
      {
        writer = null;
      }  

      // start analysing request     
      String[] typeOfReq = req.getParameterValues("type");
      String[] catOfReq  = req.getParameterValues("cat");

     // do some work

     response += "\r\n</root>";

     res.setContentLength(response.length());
     writeToClient(response);
}
private PrintWriter writer;

}

You can edit your question to add more information, instead of providing it as an "answer".
Harold L
A: 

The earlier answer got it right - your PrintWriter member variable named "writer" is the problem. Tomcat (or any other servlet container) might have one instance handle more than 1 request at the same time. This is a common cause of problems in servlet programming.

Here's some pseudo-code of what Tomcat might be doing (which is valid and expected in servlets, even though it can easily cause problems):

Servlet servlet = new ServletTest();

// in thread 1:
servlet.doPost(request1, response1);

// in thread 2:
servlet.doPost(request2, response2);

So both request1 and request2 might be running at the same time, and sharing the writer variable. If request1 sets the writer, then request2 sets the writer, then request1 writes XML, then request2 writes XML, then you'll get the output you show in your question.

Harold L
thank you, I will try it and report my results
now it works, thank you