How do i get ServletContext object in a simple class file?

前端 未结 2 955
栀梦
栀梦 2020-12-31 16:56

I am creating a simple web application. I need to get reference to ServletContext object in that class. How can i get it?

相关标签:
2条回答
  • 2020-12-31 17:15

    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:

    1. Create a ServletContextListener
    2. register it in web.xml with <listener><listener-class></listener-class></listener>
    3. on 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()
    
    0 讨论(0)
  • 2020-12-31 17:33

    I had this issue, but since I had called the class from a JSP, I simply passed the HttpServletRequest "request" reference from the JSP to the class and made the call in the class to:

    String appPath = request.getServletContext().getRealPath("");
    
    0 讨论(0)
提交回复
热议问题