What is Servlet Collaboration?
The exchange of information among servlets of a particular Java web application is known as Servlet Collaboration. This enables passing/sharing information from one servlet to the other through method invocations.
What are the principle ways provided by Java to achieve Servlet Collaboration?
The servlet api provides two interfaces namely:
- javax.servlet.RequestDispatcher
- javax.servlet.http.HttpServletResponse
These two interfaces include the methods responsible for achieving the objective of sharing information between servlets.
Using RequestDispatcher Interface
The RequestDispatcher interface provides the option of dispatching the client’s request to another web resource, which could be an HTML page, another servlet, JSP etc. It provides the following two methods:
- public void forward(ServletRequest request, ServletResponse response)throws ServletException, java.io.IOException:
The forward() method is used to transfer the client request to another resource (HTML file, servlet, jsp etc). When this method is called, the control is transferred to the next resource called. On the other hand, the include() method is used to include the content of the calling file into the called file. After calling this method, the control remains with the calling resource, but the processed output is included into the called resource.
The following diagram explains the way it works:
- public void include(ServletRequest request, ServletResponse response)throws ServletException, java.io.IOException:
The include() method is used to include the contents of the calling resource into the called one. When this method is called, the control still remains with the calling resource. It simply includes the processed output of the calling resource into the called one.
The following diagram explains how it works:

Example of using RequestDispatcher for Servlet Collaboration
The following example explains how to use RequestDispatcher interface to achieve Servlet Collaboration:
index.html
<html><head><body><formaction="login"method="post">Name:<inputtype="text"name="userName"/><br/>Password:<inputtype="password"name="userPass"/><br/><inputtype="submit"value="login"/></form></body></html>chevron_rightfilter_noneLogin.java// First java servlet that calls another resourceimportjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassLoginextendsHttpServlet {publicvoiddoPost(HttpServletRequest req,HttpServletResponse res)throwsServletException, IOException{// The method to receive client requests// which are sent using 'post'res.setContentType("text/html");PrintWriter out = response.getWriter();// fetches usernameString n = request.getParameter("userName");// fetches passwordString p = request.getParameter("userPass");if(p.equals("Thanos"){RequestDispatcher rd = request.getRequestDispatcher("servlet2");// Getting RequestDispatcher object// for collaborating with servlet2// forwarding the request to servlet2rd.forward(request, response);}else{out.print("Password mismatch");RequestDispatcher rd = request.getRequestDispatcher("/index.html");rd.include(request, response);}}}chevron_rightfilter_noneWelcome.java
// Called servlet in case password matchesimportjava.io.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassWelcomeextendsHttpServlet {publicvoiddoPost(HttpServletRequest request,HttpServletResponse response)throwsServletException, IOException{response.setContentType("text/html");PrintWriter out = response.getWriter();// fetches usernameString n = request.getParameter("userName");// prints the messageout.print("Welcome "+ n);}}chevron_rightfilter_noneweb.xml
<web-app><servlet><servlet-name>Login</servlet-name><servlet-class>Login</servlet-class></servlet><servlet><servlet-name>WelcomeServlet</servlet-name><servlet-class>Welcome</servlet-class></servlet><servlet-mapping><servlet-name>Login</servlet-name><url-pattern>/servlet1</url-pattern></servlet-mapping><servlet-mapping><servlet-name>WelcomeServlet</servlet-name><url-pattern>/servlet2</url-pattern></servlet-mapping><welcome-file-list><welcome-file>index.html</welcome-file></welcome-file-list></web-app>chevron_rightfilter_noneOutput:
index.html

If password matches:

If password doesn’t match:

Using HttpServletResponse Interface
The HttpServletResponse interface is entrusted with managing Http responses. To achieve servlet collaboration, it uses the following method:
public void sendRedirect(String URL)throws IOException;
This method is used redirect response to another resource, which may be a servlet, jsp or an html file. The argument accepted by it, is a URL which can be both, absolute and relative. It works on the client side and uses the browser’s URL bar to make a request.
Example of using sendRedirect() for redirection
The following example of a web apllication created using servlet takes the text written in the text field in the webpage, and directs it to the servlet. The servlet then redirects it to google, which then produces search results based on the text written.
index.html
<html><head><body><formaction="search"method="GET"><inputtype="text"name="name"><inputtype="submit"value="search"></form></body></html>chevron_rightfilter_none// Servlet class to redirect the text keyword// in the 'name' field to google.com// using sendRedirect()importjava.io.IOException;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;publicclassMySearcherextendsHttpServlet {protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponse response)throwsServletException, IOException{String name = request.getParameter("name");// response redirected to google.com}}chevron_rightfilter_noneweb.xml
<web-app><servlet><servlet-name>MySearcher</servlet-name><servlet-class>MySearcher</servlet-class></servlet><servlet-mapping><servlet-name>MySearcher</servlet-name><url-pattern>/search</url-pattern></servlet-mapping><welcome-file-list><welcome-file>index.html</welcome-file></welcome-file-list></web-app>chevron_rightfilter_noneOutput:
index.html

Search result

What is the difference between forward() method of RequestDiispatcher and sendRedirect() of HttpServletResponse?
Although the two methods appear to do the same thing, there are still differences between the two, which are as follows:
forward() sendRedirect() It works on the server side It works on the client side It sends the same request and response objects to another resource. It always send a new request It works only within the server. It can be used within and outside the server. Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
Recommended Posts:
- URL Rewriting using Java Servlet
- Hidden Form Field using Annotation | Java Servlet
- How to add Image to MySql database using Servlet and JDBC
- Java Servlet and JDBC Example | Insert data in MySQL
- Difference between ServletConfig and ServletContext in Java Servlet
- Difference between Java Servlet and CGI
- Javax.servlet.http.Cookie class in Java
- Difference between Servlet and JSP
- Starting with first Servlet Application
- The HttpSession Interface in Servlet
- Life Cycle of a Servlet
- File handling in Java using FileWriter and FileReader
- Calling an External Program in Java using Process and Runtime
- Counting number of lines, words, characters and paragraphs in a text file using Java
- Compressing and Decompressing files using GZIP Format in java
- Using throw, catch and instanceof to handle Exceptions in Java
- Unreachable statement using final and non-final variable in Java
- OOPS | Generalization as extension and restriction using Java
- Sort an array of pairs using Java Pair and Comparator
- Check whether array has all identical elements using Arrays.asList() and HashSet in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : akshaychopra96

