HttpServlet中init()重写时出现NullPointerException

原代码如下:


public class ServletDemo extends HttpServlet {

private static final long serialVersionUID = 1L;
private ServletConfig sercon;
public ServletConfig getSercon() {
return sercon;
}

public void setSercon(ServletConfig sercon) {
this.sercon = sercon;
}




public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


}



public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

}


@Override
public void init(ServletConfig config) throws ServletException {
this.sercon=config;
String str=sercon.getInitParameter("data");
System.out.println(str);

//直接用父类的定义getServletConfig()
sercon=this.getServletConfig();
String str1=sercon.getInitParameter("data1");
System.out.println(str1);

}
}


以上代码(部分代码)会出现NullPointerException异常

解决方法是在重写是加上:super.init(config);

你可能感兴趣的:(java,web)