我正在学习servlet,我创建了一个示例sevlet并使用注释创建了一个名为'message'的initparam。我试图在doGet()方法中访问该参数但获取nullPointerException。可能是什么问题?代码如下:
@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);
}
}
答案 0 :(得分:1)
您已经在servlet中重新定义了init方法,因此需要调用GenericServlet类的 init 方法。
例如:
public void init(ServletConfig config) throws ServletException {
super.init(config);
msg = "Message from in it method.";
}
为了避免不必这样做,GenericServlet提供了另一个不带参数的init方法,因此你可以覆盖不带参数的方法。
public void init(){
msg = "Message from in it method.";
}
init wihout争论将由GenericServlet中的那个调用。
Herer是GenericServlet中的init方法代码:
public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}