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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With