I have a RESTful web service based on JAX-RS and Jersey. I have a bunch of GET and POST Methods and inside of it I need "global" variables.
I have an initialization method with ServletContextListener and it's contextInitialized-Method for write some log files and do other stuff. In this method I want to declare variables which I can access from anywhere in my application.
here are my code:
@WebListener public class MyServletContextListener implements ServletContextListener {//these are the variables I need in my other methods public String imagePath; public int entryCount; public int registeredUsers; public Connection connection; @Override public void contextInitialized(ServletContextEvent servletContextEvent) { System.out.println("initialization of service stared"); System.out.println("reading config..."); Configuration config = ConfigManager.readConfig("../service_config.xml"); this.imagePath = config.getImagePath(); System.out.println("try to get databse connection"); connection = ConnectionHelper.getConnection(config.getDbName(), config.getDbPassword(), config.getDbUser()); System.out.println("database connection successful established"); // here are some db actions... } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { System.out.println("shutdown service"); } }
For example:At init, I read an config file, count some stats from database and read an image path-string for a directory out of my config file.
When a GET method is called, I want to read the String variable of the image path and increase a counter by 1.
@Path("/entries")public class EntryService {@GET @Path("/images/{imageId}") @Produces({"image/png"}) public Response getEntryImage(@PathParam("imageId") long imageId) { String filePath = <* HERE I NEED THE IMAGE PATH FROM INIT *>; File file = new File(filePath + imageId +".png"); if (file.exists()) { Response.ResponseBuilder response = Response.ok((Object) file); response.header("Content-Disposition", "attachment; filename=image_from_server.png"); return response.build(); } else { Response.ResponseBuilder response = Response.status(204); return response.build(); } }}
How do I realize that? (I read something about EJB and Singleton-Annotation but didn't get it work).
If a library or component needs some extra dependencies in my pom.xml file, please tell me how to implement it.