Intra-Servlet Communication
Sometimes you may need that a Servlet hands off its job to another Servlet or JSP. Intra Servlet communication can be done by means of a Dispatcher or by Redirecting the initial request.
- Dispatching is done by means of Dispatcher object which allows to complete the request without actually redirecting to user to another site, hence leaving the initial URL unchanged.
- Redirection moves the initial request to another Servlet or JSP therefore changing the initial request.
Communication between Servlets using a Dispatcher
The following example shows how a Servlet can dispatch its work to another Servlet:
@WebServlet(name = "DispatchServlet", urlPatterns = {"/dispatch"})
public class DispatchServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext sc = getServletConfig().getServletContext();
RequestDispatcher rd = null;
// Do work here
sc.getRequestDispatcher("/AnotherServlet");
rd.forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
As you can see, the capabilities of dispatching are built into the ServletContext, by calling the getRequestDispatcher method passing a String containing the name of the Servlet/JSP that you want to hand off the request to. After a RequestDispatcher object has been obtained, invoke its forward method by passing the ServletRequest and ServletResponse objects to it.
Redirection between Servlets/JSP
In the following example we can see how to redirect the request to another Servlet:
@WebServlet(name = "DispatchServlet", urlPatterns = {"/redirect"})
public class RedirectServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Do work here
response.sendRedirect(redirectUrl);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Recommended Articles
Dynamically Register Servlets and Filters in Java EE 6 Applications
Learn how to use the ServletContext class to programmatically add servlets and filters to a web application during startup with Java EE 6.
Save and Read HTTP Session State Using Cookies with Servlets
Learn how to save and read HTTP session state in cookies using Servlets for enhanced session management.
Jakarta Servlet API Tutorial: Upload and Download Files
Learn how to upload and download files using Jakarta Servlet API with Java. #Java #ServletAPI #CloudNative #Middleware #FileHandling
Implementing WebSockets in Java for Real-Time Bi-Directional Communication
Learn how to build real-time bi-directional communication using WebSockets in Java, with a step-by-step guide on creating a WebSocket application using Maven and WildFly 31.