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()方法也行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值