44

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 object associated with the ServletRequest. Is there a way to get the ServletContext object from the ServletRequest while using the Servlet 2.5 API?

Neel
  • 2,100
  • 5
  • 24
  • 47

1 Answers1

83

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();
    // ...
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555