This J2EE tip demostrates chaining method in servlets. Servlet Chaining means the output of one servlet act as a input to another servlet. Servlet Aliasing allows us to invoke more than one servlet in sequence when the URL is opened with a common servlet alias. The output from first Servlet is sent as input to other Servlet and so on. The Output from the last Servlet is sent back to the browser. The entire process is called Servlet Chaining.

// FirstServlet

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

public class FirstServlet extends HttpServlet {
  String name ;
  ServletConfig config;
  
  public void doGet(HttpServletRequest request , 
    HttpServletResponse response)
    throws ServletException , IOException {
  
    response.setContentType("text/plain");
    
    PrintWriter out = response.getWriter();
    name = request.getParameter("name");
    RequestDispatcher rd = config.
     getServletContext().getRequestDispatcher("SecondServlet");
    
    if(name!=null) {
    
      request.setAttribute("UserName",name);
      rd.forward(request , response);
      // Forward the value to another Secondservlet
    else {
      response.sendError(response.SC_BAD_REQUEST, 
        "UserName Required");
    }
  }
}


// SecondServlet

import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
  public void doGet(HttpServletRequest request , 
    HttpServletResponse response)
    throws ServletException , IOException {
    
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    String UserName = (String)request.getAttribute("UserName");
    
    // Extracting the value which is set in FirstServlet
    out.println("The UserName is "+ UserName);
  }
}