Friday, August 5, 2016

Servlet Chaining:

Servlet Chaining:

If a client request is processed by group of servlets, then that servlets are known as servlet chaining or if the group of servlets process a single client request then those servlets are known as servlet chaining.
In order to process a client request by many number of servlets then we have two models, they are forward model and include model.

Forward model:

In this model when we forward a request to a group of servlets, finally we get the result of destination servlet as a response but not the result of intermediate servlets.

Include model:

If a single client request is passed to a servlet and that servlet makes use of other group of servlets to process a request by including the group of servlets into a single servlet.
Note: One servlet can include any number of servlets where as one servlet can forward to only one servlet at a time.

FirstServlet.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class FirstServlet extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("text/html");
        PrintWriter pw = res.getWriter();
        pw.println("<h2>I AM FROM FirstServlet BEGINNING</h2>");
        ServletContext ctx = getServletContext();
        RequestDispatcher rd = ctx.getRequestDispatcher("/SS");
        rd.include(req, res);
        pw.println("<h2>I AM FROM FirstServlet ENDING</h2>");
    }
};


SecondServlet.java


import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class SecondServlet extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("text/html");
        PrintWriter pw = res.getWriter();
        pw.println("<h2>I AM FROM SecondServlet</h2>");
    }
};


Update web.xml with

<servlet>
    <servlet-name>FS</servlet-name>
    <servlet-class>FirstServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>FS</servlet-name>
    <url-pattern>/FS</url-pattern>
  </servlet-mapping>

<servlet>
    <servlet-name>SS</servlet-name>
    <servlet-class>SecondServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>SS</servlet-name>
    <url-pattern>/SS</url-pattern>
  </servlet-mapping>

Output:



Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home