Accessing ServletContext outside of a servlet

前端 未结 4 1234
长发绾君心
长发绾君心 2021-01-03 05:26

I wonder if anyone can advise on a Java webapp question?

I have a set standard Java class which has methods to set and get values of a property file. These methods a

4条回答
  •  猫巷女王i
    2021-01-03 05:27

    If you happen to use Spring then you don't have to implement your own ServletContextListener. You can use Spring's ContextLoaderListener which implements it and if registered then stores the servletContext and makes it available via a static method for later use.

    Registration in web.xml:

    
        org.springframework.web.context.ContextLoaderListener
    
    

    Then accessing the servletContext outside of a servlet is easy:

    import javax.servlet.ServletContext;
    import org.springframework.web.context.ContextLoaderListener;
    
    ServletContext servletContext = 
      ContextLoaderListener.getCurrentWebApplicationContext().getServletContext();
    

提交回复
热议问题