Jersey / ServletContext and resource loading on startup.

Posted by Raphael Jolivet on Stack Overflow See other posts from Stack Overflow or by Raphael Jolivet
Published on 2010-05-31T09:24:14Z Indexed on 2010/05/31 9:52 UTC
Read the original article Hit count: 506

Filed under:
|
|
|

Hello,

I'm kind of new in web development with Java. I am developing a web service and I've chosen REST / Jersey for it.

I want to init some stuff on startup of the service and to keep them all along the life of the service.

First question : Is the constructor of the Jersey Servlet a good place to do that ?

Basically, what I want to do is to load a config.ini file located in my WEB-INF directory. Following this help, I understand I need a ServletContext to load my file as a resource.

However, it is not clear to me how to get this ServletContext in a Jersey Servlet, as it is not really an instance of a servlet, but rather a POJO with some annotations. I wanted to try this tip, but the attribute "context" is null in the constructor. I think that Jersey might populate it after the constructor. Right ?

So how is the right way to do this ?

Here is my code so far :

/** Main REST servlet */
@Path("/")
public class Servlet {

    // ---------------------------------------------------- 
    // Constants                     
    // ---------------------------------------------------- 

    static private final String CONFIG_PATH = "/WEB-INF/config.ini";

    // ---------------------------------------------------- 
    // Attributes                     
    // ---------------------------------------------------- 

    /** Context */
    @Context ServletContext context;

    // ---------------------------------------------------- 
    // Constructor                     
    // ---------------------------------------------------- 

    /** Init the servlet */
    public Servlet() {

        // Load config.ini from WEB-INF
        Config.config = new Config(
                this.context.getResourceAsStream(CONFIG_PATH));

        // FAIL! this.context is null ...

    }

    // ---------------------------------------------------- 
    // URI Handlers                    
    // ---------------------------------------------------- 

    /** Welcome page */
    @GET
    @Path("/")
    @Produces(MediaType.TEXT_HTML)
    public String welcome() {
        return "<h1>Hi there.</h1>";
    }
}

Any help would be much appreciated. Thanks in advance,

Raphael

© Stack Overflow or respective owner

Related posts about rest

Related posts about resource