Search code examples
javaweb-servicesrestjax-wsglassfish-4

Get current web folder in Java with Jersey JAX RS.WS


This is seems easy enough, but seems like I can't find the answer at Google. I need to send a list of files at my webroot folder, kind like directory browsing.

I am using Glassfish, and JAX-RS.WS, and genson for POJO writer.

App structure like this:

download
|- build
|- dist
|- src
|- web
|  |- files

Below is my code

@Path("home")
public class HomeResource {

    @Context
    private UriInfo context;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String get() {
        return System.getProperty("user.dir"); // ??? Any idea what should be in here?
    }
}

And it gave result as :

/usr/lib/glassfish/glassfish/domains/domain1/config

I need it to point to

/sites/download/web/

or at least

/sites/download/

because I need my service to give a list like for example:

/files/item.zip
/files/document.pdf

Anyone can please help??

Thank you


Solution

  • You can get the real path from the servlet context.

    package com.scotth.jaxrsrealpath;
    
    import javax.servlet.ServletContext;
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.QueryParam;
    import javax.ws.rs.core.Context;
    import javax.ws.rs.core.MediaType;
    
    /**
     * @author scotth
     * jax-rs application deployed to /JaxRsRealPath/
     */
    @Path("sample")
    public class SampleResource {
    
        @Context ServletContext servletContext;
    
        @GET
        @Produces(MediaType.TEXT_PLAIN)
        public String getHello(@QueryParam("path") String requestedPath) {
            String path = requestedPath == null ? "/" : requestedPath;
            String actualPath = servletContext.getRealPath(path);
            return String.format("Hello, world! \nRequested path: %s\nActual path: %s", path, actualPath);
        }
    }
    

    Requesting /JaxRsRealPath/sample?path=/WEB-INF yields, in my eclipse-managed Tomcat instance, the actual filesystem path to the requested file or folder - usable with java.io.File:

    Hello, world! 
    Requested path: /WEB-INF
    Actual path: /Users/scotth/Workspaces/eclipse45-default/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/JaxRsRealPath/WEB-INF/
    

    Another example that just requests /JaxRsRealPath/sample (the code then checks the path to context root /):

    Hello, world! 
    Requested path: /
    Actual path: /Users/scotth/Workspaces/eclipse45-default/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/JaxRsRealPath/
    

    From there you can use the File APIs to get directory listings of files if you want.