Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

servlets

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?

like image 787
Neel Avatar asked May 16 '12 15:05

Neel


People also ask

How do I access servlet context?

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

What is servlet context in servlet?

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.

What is request getServletContext ()?

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() .

What is getServletContext () getRealPath ()?

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.


1 Answers

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();     // ... } 
like image 90
BalusC Avatar answered Sep 20 '22 08:09

BalusC