需要DropWizard服务资产帮助



帮助!我已经试了好几个小时了,在谷歌上搜索我能想到的任何东西。我有一个问题,我想在我的网站上显示我的静态内容,而不是我的应用程序。我修改了一个简单的helloworld应用程序:

public static void main(String[] args) throws Exception {
    Class.forName("org.sqlite.JDBC");
    new HelloWorldApplication().run(args);
}
@Override
public String getName() {
    return "hello-world";
}
@Override
public void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) {
    bootstrap.addBundle(new AssetsBundle("/assets/*", "/"));
}
@Override
public void run(HelloWorldConfiguration configuration, Environment environment) {
    final HelloWorldResource resource = new HelloWorldResource(
            configuration.getTemplate(),
            configuration.getDefaultName()
        );
    final AddResource addResource = new AddResource();
    final DeleteResource deleteResource = new DeleteResource();
    final TemplateHealthCheck healthCheck = new TemplateHealthCheck(configuration.getTemplate());
    environment.healthChecks().register("template", healthCheck);
    environment.jersey().register(resource);
    environment.jersey().register(addResource);
    environment.jersey().register(deleteResource);
}

这是我的你好世界。yml:

server:
  type: simple
  applicationContextPath: /application/hello-world
template: Hello, %s!
defaultName: Stranger

我应用了所有东西,DropWizard文档(http://dropwizard.readthedocs.org/en/latest/manual/core.html#serving-资产(表示。但我就是无法访问index.html

我还没有看到一个实际的例子来证明文档化的方式确实有效。当查看Dropwizard源代码时,我得出结论,这实际上是不可能的:Jetty应用程序上下文是由SimpleServerFactory:103:中的配置参数applicationContextPath设置的

environment.getApplicationContext().setContextPath(applicationContextPath);

然后,AssetBundlerun()(AssetBundle:109(:上注册到此应用程序上下文中

environment.servlets().addServlet(assetsName, createServlet()).addMapping(uriPath + '*');

因此,资产捆绑包总是在应用程序的YAML文件中设置的applicationContextPath提供,因此在这个applicationContextPath之外服务是不可能的(尽管文档这么说(

实现这一点的更好方法是将应用程序配置为使用/路径:

applicationContextPath: /

然后,在应用程序的代码中,在bootstrap()run()方法中,显式覆盖Jersey资源的路径,并根据您的喜好添加AssetBundles:

bootstrap.addBundle(new AssetsBundle("/static", "/"));
environment.jersey().setUrlPattern("/application/*");

我通过使用AssetsBundle((类的默认构造函数使其工作。

使用默认构造函数,您的资源将在java类路径上的目录中查找,例如

/src/main/resources/assets/

并且您必须将您的应用程序命名为ContextPath only/application

将浏览器指向静态内容的愚蠢位置

localhost:8080/application/assets/index.htm

对于Dropwizard 0.8.0及更新版本,这是通过以下配置实现的:

applicationContextPath: /
rootPath: /application

其中applicationContextPath是Jetty的Context路径,rootPath是Jersey的。

正如Geert所提到的,资产捆绑包需要在applicationContextPath中提供服务。但是,如果在引导方法中添加AssetBundle,并从run方法设置contextPath,则AssetServlet将在设置contextPath之后添加。

我的解决方案是避免使用AssetsBundle,并直接在run方法中添加AssetsServlet(在设置了contextPath之后(:

environment.getApplicationContext().setContextPath("/");
environment.servlets().addServlet("assets", new AssetServlet("/assets", "/", "index.html", StandardCharsets.UTF_8)).addMapping("/*");

相关内容

最新更新