在查看the documentation时,DropWizard似乎只能提供src / main / resources中的静态内容。我想将静态文件保存在jar文件之外的单独目录中。那可能吗?或者大多数人使用nginx / Apache作为他们的静态内容?
答案 0 :(得分:11)
答案 1 :(得分:7)
在Marcello Nuccio的回答中,我仍然花了很多时间才能做到正确,所以这就是我所做的更多细节。
我们说我有这个目录结构:
然后,这就是你要做的工作:
1)在dropwizard Application类中,添加一个新的AssetsBundle。如果您希望从其他网址提供资源,请更改第二个参数。
@Override
public void initialize(Bootstrap<AppConfiguration> bootstrap) {
bootstrap.addBundle(new AssetsBundle("/assets/", "/assets/"));
}
2)通过像这样配置maven-jar-plugin,将文档根添加到类路径中。 (获得&#34; ./ staticdocs /&#34;以正确的形式花了我一段时间。类路径是不可原谅的。)
<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)此步骤完全是可选的。如果您想从不同的根路径(例如&#34; app&#34;)提供Jersey REST资源,请将以下内容添加到您的配置YML中:
server:
rootPath: /app/*
现在您可以像这样访问静态内容,例如:
localhost:8080/assets/image.png
答案 2 :(得分:4)
使用扩展的AssetsBundle构造函数从根路径提供assets文件夹中的资源。
即。文件作为类路径中的资源加载。然后,您只需要正确设置服务的类路径。
使用默认配置,这意味着您需要调用文档根assets
,并将文档根目录的父文件夹放在类路径中。然后,例如,assets/foo.html
将在
http://localhost:8080/assets/foo.html
答案 3 :(得分:3)
官方dropwizard-bundle中有一个最新的dropwizard-configurable-assets-bundle
。你可以在github https://github.com/dropwizard-bundles/dropwizard-configurable-assets-bundle找到它。当前版本支持dropwizard 0.9.2
这可用于从任意文件系统路径提供静态文件。
答案 4 :(得分:2)
绝大多数提供静态内容的网站都是通过专用的网络服务器进行的,或者更大规模的CDN。
有时,您可能希望将应用程序部署为一个独立的单元,其中包含Dropwizard所在的所有资源。
可以让Dropwizard从类路径外部提供资产,但最简单的方法是编写自己的资产端点,从外部配置的文件路径读取。
答案 5 :(得分:1)
补充craddack的答案:正确,只要将资产添加到类路径中,就可以使用常规的AssetsBundle。 如果使用gradle和oneJar,则可以在oneJar任务的类路径中添加目录:
task oneJar(type: OneJar) {
mainClass = '...'
additionalDir = file('...')
manifest {
attributes 'Class-Path': '.. here goes the directory ..'
}
}