Initializing the JAX-RS Application

I have a REST service implemented with JAX-RS. The web service is intended for testing. My application has a HashMap that manages the objects I want to receive. How can I initialize this HashMap when the service starts, so that the HashMap some objects that I can get? I tried adding some objects to the HashMap in the constructor, but the HashMap empty when the service starts. I use the JAX-RS implementation in Jersey and set up my resources using the web.xml .

My web.xml file has the following content:

 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>OPMSimulator</display-name> <servlet> <servlet-name>MyServlet</servlet-name> <servlet-class>com.ibm.websphere.jaxrs.server.IBMRestServlet</servlet-class> <init-param> <param-name>javax.ws.rs.Application</param-name> <param-value>com.ibm.opm.mobile.prototype.TestApplication</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>MyServlet</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> </web-app> 

And my resource class has the following content:

 public class Test { private static HashMap<Integer, Database> databases; @GET @Produces(MediaType.TEXT_XML) @Path("/database/{id}") public String database(@PathParam("id")String id) { Database database = databases.get(Integer.parseInt(id)); return XMLGenerator.getXML(database); } } 
+7
source share
1 answer

Your servlet should work in the constructor (it is always called before doGet and doPost called), but otherwise you can register a listener to initialize all your things:

 import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; @WebListener public class Manager implements ServletContextListener { public void contextInitialized(ServletContextEvent event) { } public void contextDestroyed(ServletContextEvent event) { } } 

If you are not already on Servlet 3.0 and cannot upgrade and therefore cannot use the @WebListener annotation, you need to manually register it in /WEB-INF/web.xml , as shown below:

 <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"> <display-name>projectName</display-name> <listener> <listener-class>Manager</listener-class> </listener> ... </web-app> 
+9
source

All Articles