Servlets 如何从Servlet2.5中的ServletRequest获取Servlet上下文?

Servlets 如何从Servlet2.5中的ServletRequest获取Servlet上下文?,servlets,Servlets,我使用的是Tomcat6,它使用Servlet2.5。Servlet 3.0在ServletRequestAPI中提供了一个方法,该方法为与ServletRequest关联的ServletContext对象提供句柄。使用Servlet2.5API时,是否有方法从ServletRequest获取ServletContext对象?您可以通过 但是,这可能会在不需要时不必要地创建会话 但是当您已经在类的实例中时,只需使用继承的方法 或者,当您已经坐在接口实例中时,只需使用 在JSP@tgkprog中:

我使用的是Tomcat6,它使用Servlet2.5。Servlet 3.0在
ServletRequest
API中提供了一个方法,该方法为与
ServletRequest
关联的
ServletContext
对象提供句柄。使用Servlet2.5API时,是否有方法从
ServletRequest
获取
ServletContext
对象?

您可以通过

但是,这可能会在不需要时不必要地创建会话

但是当您已经在类的实例中时,只需使用继承的方法

或者,当您已经坐在接口实例中时,只需使用


在JSP@tgkprog中:天哪,请不要!只是为了测试,然后放入过滤器
ServletContext context = request.getSession().getServletContext();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ServletContext context = getServletContext();
    // ...
}
private FilterConfig config;

@Override
public void init(FilterConfig config) {
    this.config = config;
}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    ServletContext context = config.getServletContext();
    // ...
}