Example & Tutorial understanding programming in easy ways.

Which are the different ways you can communicate between servlets?

Inter-Servlet Communication

There are different ways to communicate between the different servlates. they are as follows:- 

Servlets that are present in the same web-server can communicate with each other and can also share resources between them during the execution, such as variables amongst each other.

1.By the sendRedirect() method sends the request with the new URL, which connects to this URL.
Every time it creates a new request or response object.

i.e response.sendRedirect(www.jspts.com);

Communication between servlets can also be implemented by using the RequestDisptacher interface.

RequestDispatcher object can forward a client's request to a resource or include the resource itself in the response back to the client. A resource can be another servlet, or an HTML file, or a JSP file, or may be databases etc.
There are two ways to delegate a request:-

Forward:-This method is Used to forward a request to one Servlet to another Servlet.This method must be used when output is generated by second Servlet If any other object like "PrintWriter object" is accessed by the first servlet already, then exception is thrown by this method

Example

ServletContext sc= this.getServletConfig.getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher ("/SecondServlet");
rd.forward(response,request);

Include:-This method is used to invoke one servlet from the another servlet like the forward method.
However,you can also include the output of first servlet with current servlet.
The first servlet can make use of the PrintWriter Object even after calling the include method.

Example
ServletContext sc= getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher ("/SecondServlet");
rd.include(response,request);


Read More →
Search
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!