Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call from one servlet file to another servlet file? [duplicate]

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.

like image 754
selvam Avatar asked Jan 06 '14 10:01

selvam


2 Answers

Use RequestDispatcher

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.

  1. 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.

  2. Invokes the service method, passing request and response objects. Service methods are discussed in Writing Service Methods.

like image 158
Aniket Kulkarni Avatar answered Oct 17 '22 00:10

Aniket Kulkarni


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.

like image 44
Santhosh Avatar answered Oct 17 '22 00:10

Santhosh