【发布时间】:2012-12-22 19:43:20
【问题描述】:
在查看the documentation 时,DropWizard 似乎只能提供位于 src/main/resources 中的静态内容。我想将我的静态文件保存在 jar 文件之外的单独目录中。那可能吗?还是大多数人使用 nginx/Apache 来处理他们的静态内容?
【问题讨论】:
在查看the documentation 时,DropWizard 似乎只能提供位于 src/main/resources 中的静态内容。我想将我的静态文件保存在 jar 文件之外的单独目录中。那可能吗?还是大多数人使用 nginx/Apache 来处理他们的静态内容?
【问题讨论】:
【讨论】:
根据 Marcello Nuccio 的回答,我仍然花了我一天的大部分时间才把它弄好,所以这里是我所做的更详细的说明。
假设我有这个目录结构:
那么这就是你必须做的事情:
1) 在您的 dropwizard Application 类中,添加一个新的 AssetsBundle。如果您希望从不同的 URL 提供您的资产,请更改第二个参数。
@Override
public void initialize(Bootstrap<AppConfiguration> bootstrap) {
bootstrap.addBundle(new AssetsBundle("/assets/", "/assets/"));
}
2) 通过像这样配置 maven-jar-plugin 将文档根添加到您的类路径。 (以正确的形式获取“./staticdocs/”花了我一段时间。类路径是无情的。)
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addClasspath>true</addClasspath>
</manifest>
<manifestEntries>
<Class-Path>./staticdocs/</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
3) 这一步完全是可选的。如果您想从不同的根路径(例如“app”)提供您的 Jersey REST 资源,请将以下内容添加到您的配置 YML:
server:
rootPath: /app/*
现在您可以像这样访问您的静态内容,例如:
localhost:8080/assets/image.png
【讨论】:
assets 文件夹放在src/main/resources 中来避免使用maven-jar-plugin。
user manual 说:
使用扩展的 AssetsBundle 构造函数从根路径为 assets 文件夹中的资源提供服务。
即这些文件作为资源从类路径加载。那么您只需要正确设置服务的类路径即可。
使用默认配置,这意味着你需要调用文档根assets,并将文档根的父文件夹放在类路径中。然后,例如,assets/foo.html 将在
http://localhost:8080/assets/foo.html
【讨论】:
rsync 来更新最新部署文件的中间副本。这是非常快速和可靠的。
在官方 dropwizard-bundles 中维护了最新的 dropwizard-configurable-assets-bundle。你可以在 github https://github.com/dropwizard-bundles/dropwizard-configurable-assets-bundle 找到它。当前版本支持 dropwizard 0.9.2
这可用于从任意文件系统路径提供静态文件。
【讨论】:
绝大多数提供静态内容的网站都是通过专用的网络服务器来实现的,或者在更大范围内通过CDN。
有时,您可能希望将应用程序部署为一个独立的单元,其中包含 Dropwizard 的所有资产。
可以让 Dropwizard 从类路径外部提供资产,但最简单的方法是编写您自己的资产端点,该端点从外部配置的文件路径中读取。
【讨论】:
补充 craddack 的回答:正确,只要将资产添加到类路径中,就可以使用常规 AssetsBundle。 如果使用 gradle 和 oneJar,可以在 oneJar 任务中的类路径中添加目录:
task oneJar(type: OneJar) {
mainClass = '...'
additionalDir = file('...')
manifest {
attributes 'Class-Path': '.. here goes the directory ..'
}
}
【讨论】: