Java Sending response from one servlet to another
Java Sending response from one servlet to another
There are some scenarios where we need to forward request to another Servlet and include their response in the main servlet. Sending response from one servlet to another was never easy just follow the script below.
For example if we have 2 Servlet, One is named as MainPage and other is External.
Content of the External Servlet looks like this
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class External extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); try { out.println("<h1>This is the External Servlet Page And I will Get Loaded With MainPage Servlet</h1>"); out.close(); } catch(IOException ex) { out.println("Error External"); } } }
Now all you have to do is write a Servlet by importing javax.servlet.RequestDispatcher
import javax.servlet.RequestDispatcher;
Then you need to forward the request and get the response using
RequestDispatcher dispatcher = request.getRequestDispatcher("/External"); dispatcher.include(request, response);
Note:- /External is the URI of the Servlet that will get included inside the MainPage Servlet.
The MainPage Servlet code will look like this
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.RequestDispatcher; public class MainPage extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); try { out.println("<html>"); out.println("<head>"); out.println("<title>This is the Main Web Page</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>This is the Main Page Loaded From MainPage Servlet</h1>"); //This Part Loads The Second Servlet RequestDispatcher dispatcher = request.getRequestDispatcher("/External"); dispatcher.include(request, response); out.println("</body>"); out.println("</html>"); out.close(); } catch(IOException ex) { out.println("Error MainPage"); } } }
Once you load the URL with http://websitename/MainPage it will incude the External Servlet contents along with the MainPage Servlet.