Issue
I am using net beans 7.1 and I create one JSP file with two servlet files. like:
index.jsp --->servlet1.java --->servlet2.java
I give some value from index.jsp
file and send to servlet1.java
.
In this servlet1.java
file I call servlet2.java
file.
Then it throws NullPointerException
. How can I solve this?
My code like this:
index.jsp
<form action="servlet1" method="post">
servlet1.java
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
..................
..................
..................
servlet2 ob=new servlet2();
ob.doPost(request, response);
..................
..................
..................
}
Then it throws NullPointerException
.
Solution
RequestDispatcher rd = request.getRequestDispatcher("servlet2");
rd.forward(request,response);
RequestDispatcher
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.
Update
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.
Answered By - Aniket Kulkarni
Answer Checked By - Mildred Charles (JavaFixing Admin)