tags:

views:

38

answers:

2

I am just beginning with Servlets and managed to have some servlets that act as individual URLs for populating a database for some dummy testing. Something of the form:

public class Populate_ServletName extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
     resp.setContentType("text/plain");
     //Insert records
     //Print confirmation
  }
}

I have about 6 such servlets which I want to execute in a sequence. I was thinking of using setLocation to set the next page to be redirected but was not sure if this is the right approach because the redirects should happen after the records have been inserted. Specifically, I am looking for something like this:

public class Populate_ALL extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
     resp.setContentType("text/plain");
     //Call Populate_1
     //Call Populate_2
     //Call Populate_3
     //...
  }
}

Any suggestions?

+1  A: 

It looks like what you may need is a service that each of the servlets can use to perform some work. Then the servlets are not depending one and another, but rather all using the service.

However, here is an explanation of forwarding or redirecting requests.

Sualeh Fatehi
@Sualeh: +1. Thank you for the link. Will look into it.
Legend
+2  A: 

Use RequestDispatcher#include() on an URL matching the url-pattern of the Servlet.

public class Populate_ALL extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     response.setContentType("text/plain");
     request.getRequestDispatcher("/populateServlet1").include(request, response);
     request.getRequestDispatcher("/populateServlet2").include(request, response);
     request.getRequestDispatcher("/populateServlet3").include(request, response);
     //...
  }
}

Note: if those servlets cannot be used independently, then this is the wrong approach and you should be using standalone Java classes for this which does not extend HttpServlet. I think the Builder Pattern may be of interest.

The RequestDispatcher#forward() is not suitable here since it throws IllegalStateException when the response headers are already committed. This will be undoubtely the case when you pass the request/response through multiple servlets which each writes to the response.

The HttpServletResponse#sendRedirect() is absolutely not suitable here since it implicitly creates a brand new request and response, hereby trashing the original ones.

BalusC
@BalusC: +1 for this. The servlets can be used independently. Thank you for the suggestion.
Legend