
How to call a servlet from another servlet in Java?

You can call another servlet by using requestDispatcher() or sendRedirect() according to application requirement.
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CallServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Calling another servlet by using RequestDispatcher...");
ServletContext context=this.getServletContext();
RequestDispatcher requestDispatcher=context.getRequestDispatcher("/servlet1");
requestDispatcher.forward(request, response);
System.out.println("Calling another servlet by using SendRedirect...");
response.sendRedirect("/Servlet2");
}
}
In RequestDispatcher the target servlet contain the same request/response object.So you can pass data between them by setting attribute as request.setAttribute() and get data by request.getAttribute(). In sendRedirect() new request is generated from the client side so you can pass data only through session or setting parameter as (url?name=value);
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.