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.

7 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Attend The Data Scientist Courses From ExcelR. Practical Data Scientist Courses Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Scientist Courses. Data Scientist Courses

    ReplyDelete
  3. Thank you for sharing wonderful information with us.Really useful for everyone data scientist courses

    ReplyDelete
  4. Thanks for sharing this information. I really like your blog post very much. You have really shared a informative and interesting blog post with people..
    data science institutes in hyderabad

    ReplyDelete
  5. I have bookmarked your site since this site contains significant data in it. You rock for keeping incredible stuff. I am very appreciative of this site.
    data analytics training in hyderabad

    ReplyDelete