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);
}
}
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();
}