gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:48:18 25 4
gpt4 key购买 nike

给定在 Tomcat 下部署的 JAX-RS Web 服务,我如何通过指定 http://site/path/file 等 URL 使某些文件可以直接从浏览器访问?

假设我有返回 HTML 网页的网络服务方法,我需要在该页面内加载存储在网络服务目录中的 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>";
}

我应该将文件放在 Web 服务目录(WebContentMETA-INFWEB-INF 等)中的什么位置?我应该在 html 页面中放置路径吗?

最佳答案

您基本上有三个选择:absolute, relative or root links .

如果您将文件作为外部资源,则绝对链接有效。大多数情况下,相对 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>";
}

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

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

类似于:

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

无需更改一行代码。

关于web-services - 如何通过指定 URL 访问 JAX-RS Web 服务目录中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15408639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com