You can use the listener to initialize the variables and set the context attribute before starting the web application, something like the following
package org.paulvargas.shared; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class LoadConfigurationListener implements ServletContextListener { public void contextInitialized(ServletContextEvent sce) {
This listener is configured in web.xml .
<listener> <listener-class>org.paulvargas.shared.LoadConfigurationListener</listener-class> </listener>
You can use the @Context annotation to enter the ServletContext and get the attribute.
package org.paulvargas.example.helloworld; import java.util.*; import javax.servlet.ServletContext; import javax.ws.rs.*; import javax.ws.rs.core.*; @Path("/world") public class HelloWorld { @Context private ServletContext context; @GET @Produces("text/plain; charset=UTF-8") public String getGreeting() {
source share