How do I access files in a JAX-RS web service directory by specifying their URL?

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

Say I have a web service method that returns an HTML web page, and I need to load a CSS file or image file stored in the web service directory on this page. For instance:

 @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 in web service directories ( WebContent , META-INF , WEB-INF , etc.) and which path should be placed on the html page?

+4
source share
1 answer

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

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

Thus, the preferred way is to have styles, scripts, or images at known positions in your application and access them with root links (scrambled URL prefixes) like /Images/image.jpg .

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

These links resolve the root of your application, so you must consider the path to the context. A basic example might be the following:

 @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 have these paths in the .properties file and loaded as a general configuration. This will 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 the line of code.

+2
source

Source: https://habr.com/ru/post/1469217/


All Articles