Neel
Neel

Reputation: 2100

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

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?

Upvotes: 44

Views: 79108

Answers (1)

BalusC
BalusC

Reputation: 1108537

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();
    // ...
}

Upvotes: 83

Related Questions