Question

I have code like so:

@Path("/test")
public class MyServlet {
    static final Dictionary stuff = new Hashtable();

    @GET
    public Response response(@QueryParam....)
        throws FileNotFoundException {


         File directory = new File("test\");
         File[] directoryListing = directory.listFiles();
                 while .......

I want to do this part where I open the files and put them in my dictionary on startup, not with every request, how can I do this? So I can use the dictionary inside the response method later.

Was it helpful?

Solution

You can use a static initialization block which will run once the class is loaded:

public class MyServlet {

    static final Dictionary stuff = new Hashtable();

    static {
        // load files
    }

    // ...
}

This technique is not special to jax-rs/jersey or any other framework, it's a language feature.


Move the code to a method if you want to be able to call it again later:

public class MyServlet {

    static final Dictionary stuff = new Hashtable();

    static {
        // load at startup
        reloadDictionary();
    }

    // call this whenever you want to reload the files
    static void reloadDictionary() {
        // reload files
    }

    // ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top