8

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.

peterh
  • 11,875
  • 18
  • 85
  • 108
selvam
  • 1,177
  • 4
  • 18
  • 40

2 Answers2

17

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.

Aniket Kulkarni
  • 12,825
  • 9
  • 67
  • 90
2

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.

Santhosh
  • 8,181
  • 4
  • 29
  • 56