can we override init(ServletConfig config) method in servlet class in J2ee ?

Yes , we can override init(ServletConfig config) into servlet , but when you retrive ServletCofig object into inside servlet give Nullpointer Exception .

Code:
package com.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class servlettest extends HttpServlet {
    private static final long serialVersionUID = 1L;
   
   
    public void init(ServletConfig config) throws ServletException
    {
    }
/**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name=request.getParameter("first_name");
        System.out.println("The name is"+name);
        try {
         ServletConfig config=getServletConfig();
        System.out.println("The get Servlet config is"+config.getServletContext());
        System.out.println("The servlet name is"+config.getServletName());
        }
        catch(Exception ex)
        {
            System.out.println("The exception is"+ex);
        }
        RequestDispatcher rd= request.getRequestDispatcher("success.jsp");
        rd.forward(request, response);
       
    //    super.doGet(request, response);
    }

   

}


OUTPT:

The name is
The exception isjava.lang.NullPointerException



In above code it will clear that Servlet container intstantiate servlet and give server and enviornment information to particular servlet
through init(ServletConfig config) . 

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.