When using the forward method of the RequestDispatcher object to pass control from a servlet called ABCServlet to another servlet named XYZServlet, the easiest is to place the class files of both ABCServlet and XYZServlet in the same directory. This way, ABCServlet can be invoked from the URL
http://domain/VirtualDir/servlet/ABCServlet and XYZServlet can be called from the URL
http://domain/VirtualDir/servlet/XYZServlet. Using the forward method is then straightforward. You can use the getRequestDispatcher from the ServletRequest interface passing the name of the second servlet. In ABCServlet, you can write this code:
RequestDispatcher rd = request.getRequestDispatcher("XYZServlet"); rd.forward(request, response);
You don't need to include the / character before XYZServlet. This way is easiest because you don't need to worry about the paths of both servlets at all.
The harder way would be trying to pass this String to the getRequestDispatcher of ServletRequest:
"/servlet/XYZServlet"
If you have to invoke the forward method of a RequestDispatcher object obtained from the getRequestDispatcher of the ServletContext, you need to pass "/VirtualDir/servlet/XYZServlet" as the path argument, such as:
RequestDispatcher rd = getServletContext().getRequestDispatcher("/servlet/XYZServlet");
rd.forward(request, response);To use the getNamedDispatcher method, your code would become:
RequestDispatcher rd = getServletContext().getNamedDispatcher("XYZServlet");
rd.forward(request, response);