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:
<form action="servlet1" method="post">
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
..................
..................
..................
servlet2 ob=new servlet2();
ob.doPost(request, response);
..................
..................
..................
}
Then it throws NullPointerException
.
Use RequestDispatcher
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With