I am creating a simple web application. I need to get reference to ServletContext object in that class. How can i get it?
You'd better pass it as argument to the constructor of your object, or set it using a setter method.
In fact, you may obtain the context attribute that is relevant to your object and pass only it via constructor/setter. For example:
YourClass obj =
new YourClass((AnotherClass) servletContext.getAttribute("yourAttribute"));
A much worse and more complication option is to:
ServletContextListener
<listener><listener-class></listener-class></listener>
contextInitialized(..)
get the ServletContext
from the event and store it in a singleton - a static field somehwere. Alternatively, you can do this on each request, using a ServletRequestListener
and store it in a ThreadLocal
instead.
Then you can obtain the value via calling your singleton/threadlocal holder like this:
ServletContextHolder.getCurrentServletContext()
我有这个问题,但是因为我从JSP调用了类,所以我只是将JSP中的HttpServletRequest“request”引用传递给了类,并在类中调用了:
String appPath = request.getServletContext().getRealPath("");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.