【问题标题】:How to get the Servlet Context from ServletRequest in Servlet 2.5?如何从 Servlet 2.5 中的 ServletRequest 获取 Servlet 上下文?
【发布时间】:2012-05-24 04:41:06
【问题描述】:

我正在使用使用 Servlet 2.5 的 Tomcat 6。 Servlet 3.0 中的ServletRequest API 中提供了一个方法,该方法提供了与ServletRequest 关联的ServletContext 对象的句柄。有没有办法在使用 Servlet 2.5 API 时从 ServletRequest 获取 ServletContext 对象?

【问题讨论】:

    标签: servlets


    【解决方案1】:

    您可以通过HttpSession#getServletContext()获取它。

    ServletContext context = request.getSession().getServletContext();
    

    然而,这可能会在不需要时不必要地创建会话。

    但是当您已经坐在HttpServlet 类的实例中时,只需使用继承的GenericServlet#getServletContext() 方法。

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = getServletContext();
        // ...
    }
    

    或者,当您已经坐在Filter 接口的实例中时,只需使用FilterConfig#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();
        // ...
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-25
    • 2014-03-06
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 2016-06-20
    • 2014-04-25
    • 1970-01-01
    相关资源
    最近更新 更多