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?
Use
RequestDispatcher#include()on an URL matching theurl-patternof the Servlet.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. In your specific case, I think the Builder Pattern may be of interest.The
RequestDispatcher#forward()is not suitable here since it throwsIllegalStateExceptionwhen 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 newrequestandresponse, hereby trashing the original ones.See also: