Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access files within a JAX-RS web service directory by specifying their URL?

Given a JAX-RS web service deployed under Tomcat, how can I make some of the files accessible directly from the browser by specifying the URL like http://site/path/file?

Let's say I have web service method returning an HTML web page and I need, within that page, to load a CSS file or an image file stored in the web service directory. For example:

@GET
@Path("/")
@Produces(MediaType.TEXT_HTML)
public synchronized String root() {
    String head = "<head><link href=\"path/style.css\" rel=\"stylesheet\"></head>";
    String head = "<body><img src=\"path/image.jpg\"/></body>";
    return "<html>"+ head + body + "<html>";
}

Where should I put the file within the web service directories (WebContent, META-INF, WEB-INF, etc) and what path should I put in the html page?

like image 346
Marco Lackovic Avatar asked Nov 04 '22 02:11

Marco Lackovic


1 Answers

You basically have three choices: absolute, relative or root links.

Absolute links work if you have your files as external resources. Relative URLs are most of the time a pain for static resources like styles, scripts or images because they must be resolved starting from the location that refers to them (they can be in various forms like images/image.jpg, ../image.jpg, ../images/image.jpg etc).

So a preferred way is to have styles, scripts or images at known positions within your application and access it with root links (slash prefixed URLs) like /Images/image.jpg.

Your folders must be in the folder of the application (WebContent in your question). Placing something under WEB-INF hides the resource and clients can no longer access it.

These links resolve to the root of your application so you must account for the context path. A basic example would be something like this:

@GET
@Path("whatever_path_might_be")
@Produces(MediaType.TEXT_HTML
public String root(@Context ServletContext ctx) {
    String ctxPath = ctx.getContextPath();
    String stylesFolder = ctxPath + "/Styles";
    String imagesFolder = ctxPath + "/Images";

    String head = "<head><link href=\"" + stylesFolder + "/style.css\" rel=\"stylesheet\"></head>";
    String body = "<body><img src=\"" + imagesFolder + "/image.jpg\"/></body>";
    return "<html>"+ head + body + "<html>";
}

This is a basic example, I'm sure you can find ways to improve it. You could event have these paths in a .properties file and loaded as general configuration. This will later allow you to switch from something like:

resources.cssFolder=/appcontext/styles
resources.imgFolder=/appcontext/images

to something like:

resources.cssFolder=http://external.server.com/styles
resources.imgFolder=http://external.server.com/images

without changing a line of code.

like image 99
Bogdan Avatar answered Nov 09 '22 08:11

Bogdan