Showing posts with label ServletContext. Show all posts
Showing posts with label ServletContext. Show all posts

Thursday, April 30, 2015

How to load a resource from WEB-INF directory of a Web Archive (WAR)

The Maven Convention


Anything that is placed within the "src/main/resources" folder will be accessible from the classpath. In the case of a web application (deployed WAR), the content will will be generated into the "WEB-INF/classes" section of the WAR file.

In this case, I have a lucene directory copied here:
Fig 1: View from within Eclipse
The JAX-RS class looks like this:

package com.mycompany;

import java.io.File;

import javax.servlet.ServletContext;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;


@Path("/path")
public class MyREST {

 @javax.ws.rs.core.Context
 ServletContext    context;

 @GET
 @Path("/get")
 @Produces(MediaType.APPLICATION_JSON)
 public Object getit(@@QueryParam("text") String text) {
  
  String fullPath = context.getRealPath("/WEB-INF/classes/lucene");
  logger.info("Acquired Lucene Path from Context (path = %s, exists = %s)", fullPath, new File(fullPath).exists());

  // perform the query logic ...
  // return the JSON result
 }
}


Note the use of the ServletContext to access the resource.

The generated WAR file looks like this:
Fig 2: Maven-generated WAR file
The WAR file was generated using Maven.


References

  1. [StackOverflow] Files under src/main/resources go into WEB-INF/classes
  2. [StackOverflow] Additional configuration for the Maven POM
    1. You can specify directories and files relative to the POM that should also be copied into the WEB-INF/classes directory.