Servlet中的getServletContext的使用注意事项
在doget或dopost中直接获取ServletContext对象
getServletContext()方法是ServletConfig接口定义的方法,在servlet中可以直接调用getServletContext()来获取ServletContext对象
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("上下文参数:"+getServletContext().getInitParameter("age"));
}
如果Servlet重写了带有ServletConfig参数的init方法,那么调用getServletContext()时会引发空指针异常
@Override
public void init(ServletConfig config) throws ServletException {
//
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(getServletContext());
}
引发空指针异常是GenericServlet中的getServletConfig()为空引发的
@Override
public ServletContext getServletContext() {
return getServletConfig().getServletContext();
}
那么也就意味着在servlet中获取ServletConfig对象就是空的
@Override
public void init(ServletConfig config) throws ServletException {
//
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(getServletConfig()); //null
//System.out.println(getServletContext());
}
这是因为父类的init(ServletConfig config)里对ServletConfig对象进行了初始化
@Override
public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}
而我们重写了init方法,ServletConfig就是空的,所以我们要在重写的init方法中调用父类的init方法对ServletConfig赋值
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(getServletContext());
}
或者通过request对象的getServletContext来获取ServletContex
@Override
public void init(ServletConfig config) throws ServletException {
//super.init(config);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(req.getServletContext());
}
或者选择重写的是public void init()方法也行。