문제

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.

도움이 되었습니까?

해결책

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
    }

    // ...
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top