How to get the Servlet Context from ServletRequest in Servlet 2.5?

后端 未结 1 928
轮回少年
轮回少年 2020-12-05 22:29

I am using Tomcat 6 which uses Servlet 2.5. There is a method provided in Servlet 3.0 in the ServletRequest API which gives a handle to the ServletContext

相关标签:
1条回答
  • 2020-12-05 23:21

    You can get it by the HttpSession#getServletContext().

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

    This may however unnecessarily create the session when not desired.

    But when you're already sitting in an instance of the HttpServlet class, just use the inherited GenericServlet#getServletContext() method.

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

    Or when you're already sitting in an instance of the Filter interface, just use 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();
        // ...
    }
    
    0 讨论(0)
提交回复
热议问题