How to execute multiple servlets in sequence?

I am just starting with Servlets and I have some servlets that act as separate URLs to populate the database for some dummy testing. Something like 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 that I want to execute in sequence. I was thinking about using setLocation to redirect the next page, but was not sure if this is the right approach, because redirects should happen after the records have been inserted. In particular, 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?

+3
source share
2 answers

Use RequestDispatcher#include()the URL corresponding to the url-patternservlet.

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);
     //...
  }
}

. , , Java, HttpServlet. , Builder Pattern .

RequestDispatcher#forward() , IllegalStateException, . , , , / , .

HttpServletResponse#sendRedirect() , request response, .

. :

+5

, , . , .

.

+1

All Articles