-2

I am learning servlets and I created a sample sevlet and created a initparam called 'message' using annotation. I am trying to access that param in doGet() method but getting nullPointerException. What can be the problem? The code is given below:

@WebServlet(
        description = "demo for in it method", 
        urlPatterns = { "/" }, 
        initParams = { 
                @WebInitParam(name = "Message", value = "this is in it param", description = "this is in it param description")
        })
public class DemoinitMethod extends HttpServlet {
    private static final long serialVersionUID = 1L;
    String msg = "";

    /**
     * @see HttpServlet#HttpServlet()
     */
    public DemoinitMethod() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Servlet#init(ServletConfig)
     */
    public void init(ServletConfig config) throws ServletException {
        msg = "Message from in it method.";
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println(msg);

        String msg2 = getInitParameter("Message");
        out.println("</br>"+msg2);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
DanielBarbarian
  • 5,093
  • 12
  • 35
  • 44
Arpit Shukla
  • 21
  • 2
  • 10

1 Answers1

1

You have redefined the init method in your servlet so you need to call init method of GenericServlet class.

ex:

public void init(ServletConfig config) throws ServletException {
        super.init(config);

        msg = "Message from in it method.";
    }

To save you from having to do so, GenericServlet provide another init method without argument, thus you can override the one which doesn't take argument.

public void init(){
 msg = "Message from in it method.";
}

the init wihout arguement will be called by the one in GenericServlet.

Herer is the code of init method in GenericServlet:

public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}
Abass A
  • 713
  • 6
  • 14
  • I got your point. But I still didn't get how can I print value of the param 'message' in doGet() method which was created by me in annotation at the beginning of servlet. – Arpit Shukla Jun 30 '17 at 14:38
  • `getInitParameter("Message")` is correct, your nullpointer exception was probably due to your ServletConfig variable which was not initialized because you overrided the init method. Just change your code as explained and you should be fine. – Abass A Jun 30 '17 at 14:42