Access to ServletContext outside the servlet

I wonder if anyone could advise a Java webapp question?

I have a standard standard Java class that has methods for setting and getting property file values. These methods are used in the system area and are called by servlets and class methods without a servlet.

But I would like to use ServletContextListener to set the paths to the properties file around the world, and not to hard-code them or save them to the database.

ServletContextListener can be used to set global variables for servlets with context.setAttribute ("PROP_FILE_PATH", "C: \ ..."). But is there a way to access these variables outside of servlets, or can ServletContext servlets access external servlets?

I do not think that passing ServletContext as a parameter to the class method I should receive and setting the values ​​of the properties file would be a viable option due to the number of calls.

thanks

Martin

+4
source share
4 answers

You can always save your settings in a different place than the servlet context, say, a set of static variables in the configuration class. Then it ServletContextListenercan set these variables at startup, and any other code can access these statistics, regardless of whether it has access to it ServletContextor not.

+8
source

ServletContext can be used in the context or boundaries of a servlet.

jndi, , .

, , ( script ). , , {} . , . , jndi.

+1

ServletContext ServletContextListener, , . , . , HttpServletRequest . , .

ServletContext application = req.getSession().getServletContext();

, , , , .

+1

If you use Spring, you do not need to implement your own ServletContextListener. You can use the Spring ContextLoaderListener, which implements it, and if it is registered, it saves the servletContext and makes it available through the static method for future use.

Registration in web.xml:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

Then accessing the servletContext outside the servlet is easy:

import javax.servlet.ServletContext;
import org.springframework.web.context.ContextLoaderListener;

ServletContext servletContext = 
  ContextLoaderListener.getCurrentWebApplicationContext().getServletContext();
0
source

Source: https://habr.com/ru/post/1717841/


All Articles