如何通过指定URL来访问JAX-RS Web服务目录中的文件?

Mar*_*vic 5 rest tomcat web-services jax-rs

鉴于在Tomcat下部署了JAX-RS Web服务,如何通过指定URL来直接从浏览器访问某些文件http://site/path/file

假设我有Web服务方法返回HTML网页,我需要在该页面中加载存储在Web服务目录中的CSS文件或图像文件.例如:

@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>";
}
Run Code Online (Sandbox Code Playgroud)

我应该在哪里放置Web服务目录中的文件(WebContent,META-INF,WEB-INF等),我应该把HTML页中的路径是什么?

Bog*_*dan 2

您基本上有三种选择:绝对链接、相对链接或根链接

如果您将文件作为外部资源,则绝对链接有效。大多数时候,相对 URL 对于样式、脚本或图像等静态资源来说是一种痛苦,因为必须从引用它们的位置开始解析它们(它们可以采用各种形式,例如等images/image.jpg, ../image.jpg, ../images/image.jpg)。

因此,首选方法是在应用程序中的已知位置放置样式、脚本或图像,并使用根链接(斜杠前缀 URL)访问它,例如/Images/image.jpg.

您的文件夹必须位于应用程序的文件夹中(WebContent在您的问题中)。将某些内容放在 WEB-INF 下会隐藏资源,客户端将无法再访问它。

这些链接解析为应用程序的根目录,因此您必须考虑上下文路径。一个基本的例子是这样的:

@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>";
}
Run Code Online (Sandbox Code Playgroud)

这是一个基本的例子,我相信你可以找到改进它的方法。您可以将这些路径放在 .properties 文件中并作为常规配置加载。稍后这将允许您从以下内容切换:

resources.cssFolder=/appcontext/styles
resources.imgFolder=/appcontext/images
Run Code Online (Sandbox Code Playgroud)

像这样的东西:

resources.cssFolder=http://external.server.com/styles
resources.imgFolder=http://external.server.com/images
Run Code Online (Sandbox Code Playgroud)

无需更改一行代码。