How to load and store global variables in Jersey / Glassfish

I am creating a RESTful web service that wraps an outdated provider API. Some external configuration is required and will be stored on the server either in a file or in rdbms. I am using Jersey 1.11.1 in Glassfish 3.1.2. This configuration data is all in the format of strings / String values.

My first question is: where can I store global variables / instances in Jersey so that they persist between requests and are accessible to all resources? If it was a pure Servlet application, I would use ServletContext to accomplish this.

The second part of the question is how to load the download after the Jersey server has loaded Again, my servlet analogy would be to find the equivalent of the init () method.

+6
source share
2 answers

@Singleton @Startup EJB meets your requirements.

 @Singleton @Startup // initialize at deployment time instead of first invocation public class VendorConfiguration { @PostConstruct void loadConfiguration() { // do the startup initialization here } @Lock(LockType.READ) // To allow multiple threads to invoke this method // simultaneusly public String getValue(String key) { } } @Path('/resource') @Stateless public class TheResource { @EJB VendorConfiguration configuration; // ... } 

EDIT: added annotation in Graham comment

+11
source

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) { // read file or rdbms ... ServletContext context = sce.getServletContext(); // set attributes ... } public void contextDestroyed(ServletContextEvent sce) { ServletContext context = sce.getServletContext(); // remove attributes ... } } 

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() { // get attributes String someVar = (String) context.getAttribute("someName") return someVar + " says hello!"; } } 
+7
source

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


All Articles