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?
There's no other way to obtain the servlet context than via HttpSession#getServletContext() . @Override public void sessionDestroyed(HttpSessionEvent event) { ServletContext context = event. getSession(). getServletContext(); // ... }
Interface ServletContext. public interface ServletContext. Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine.
getServletContext() you can call directly is only when your code is in a class that extends HttpServlet. That is because HttpServlet base class has this method defined. ServletContext returned by request. getSession(). getServletContext() is same as getServletContext() .
The ServletContext#getRealPath() is intented to convert a web content path (the path in the expanded WAR folder structure on the server's disk file system) to an absolute disk file system path. The "/" represents the web content root.
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(); // ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With