Servlet Collaboration

Servlet Collaboration :

Servlet Collaboration means servlets can pass the shared information directly from one servlet .
There are several techniques
-Using sendRedirect() method on Response object.
-Using RequestDispatcber interface
Using sendRedirect() method:
Syntax :
public void sendRedirect(String URLlocation) throws IOException
This method sends a temporary redirect response to the client using the specified redirect location URL.
This method can accept relative URLs, the servlet container must convert the relative URL to an absolute sending the response to the client.
If the response has already been committed, this method throws an IllegalStateException.
After using this method, the response should be considered to be committed and should not be written to.
Using RequestDispatcher interface: 
This interface encapsulates a reference of another web resource at a specified path within the scope of same servlet context.

This interface’s object is used to dispatch the request to other servlet, jsp and html file.

RequestDispatcher interface has two methods:
  • void forward(ServletRequest request, ServletResponse response)  : 
    • Forward a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
    • This method allows one servlet to do preliminary processing of a request and another resource to generate the response.
    • For a RequestDispatcher obtained via setRequestDispatcher(), the ServletRequest object has its path elements and parameters adjusted to match the path of the target resource.
    • This method should be called before the response has been committed to the client (before response body output has been flushed).
    • If the response already has been committed, this method throws an IllegalStateException.
    • Uncommitted output in the response buffer is automatically cleared before the forward.

working of forward method

  • void include(ServletRequest request, ServletResponse response) :
    • Include the content of a resource (servlet, JSP page, HTML file) in the response.
    • Response of second servlet is included in the response of the first servlet that is being sent to the client.
    • The ServletResponse object has its path elements and parameters remain unchanged from the caller’s.
    • In essence, this method enables programmatic server-side includes.
    • Included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.
 working of include method
Example :





Leave a Reply

Your email address will not be published. Required fields are marked *