How can I call from one servlet file to another servlet file?
RequestDispatcher rd = request.getRequestDispatcher("servlet2"); rd.forward(request,response);
Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server.
No need to create an object of servlet manually, just simply use
RequestDispatcher to call servlet because web container controls the lifecycle of servlet.
From Oracle JavaEE docs Servlet Lifecycle
The lifecycle of a servlet is controlled by the container in which the servlet has been deployed.
When a request is mapped to a servlet, the container performs the following steps.
If an instance of the servlet does not exist, the web container
Loads the servlet class.
Creates an instance of the servlet class.
Initializes the servlet instance by calling the init method. Initialization is covered in Creating and Initializing a Servlet.
Invokes the service method, passing request and response objects. Service methods are discussed in Writing Service Methods.
What are you trying here,
servlet2 ob=new servlet2(); ob.doPost(request, response);
Its not necessary to create an object explicitly for a servlet, Web container creates an instance for a servlet and shares it during the app's lifetime . Though you have created an object here, it will return the existing object only.
You can is instead go for Request Dispatcher or page Redirect.