LoginSignup
2
2

More than 5 years have passed since last update.

DropwizardのAssets

Posted at

Environmentsを確認。
Assetsを試す。
動作確認用に作ったのでResource、Health Checkは適当。

Dropwizardのバージョンは0.6.2。

AssetsBundle

Service#initializeでBootstrap#addBundleを使ってAssetsBundleを追加する。
src/main/resources/assetsのファイルを/に割り当てる。

AssetsService.java
package example.core.assets;

import com.yammer.dropwizard.Service;
import com.yammer.dropwizard.assets.AssetsBundle;
import com.yammer.dropwizard.config.Bootstrap;
import com.yammer.dropwizard.config.Environment;

public class AssetsService extends Service<AssetsConfiguration> {
    @Override
    public void initialize(Bootstrap<AssetsConfiguration> bootstrap) {
        bootstrap.setName("assets");

        bootstrap.addBundle(new AssetsBundle("/assets/", "/"));
    }

    @Override
    public void run(AssetsConfiguration configuration, Environment environment) throws Exception {
        environment.addResource(new AssetsResource());
        environment.addHealthCheck(new AssetsHealthCheck());
    }

    public static void main(String[] args) throws Exception {
        new AssetsService().run(args);
    }
}

index.html

src/main/resources/assetsに以下のindex.htmlを作成。
jquery-2.0.3.min.jsも同じディレクトリに配置する。

index.html
<html>
<head>
    <script src="jquery-2.0.3.min.js"></script>
    <script>
        $(function(){
            $.ajax({
                url: '/service/hello',
                success: function(data) {
                    $('#hello').text(data.content);
                }
            });
        });
    </script>
</head>
<body>
    <span id="hello"></span>
</body>
</html>

設定ファイル

JAX-RSのルートを変更する。
Assetsを使用する場合は必須。

assets.yml
http:
  rootPath: /service/*

以上の実装、設定で http://localhost:8080/index.html を表示するとhelloと表示される。

その他今回書いたもの

AssetsConfiguration.java
package example.core.assets;

import com.yammer.dropwizard.config.Configuration;

public class AssetsConfiguration extends Configuration {
}
AssetsResource.java
package example.core.assets;

import com.yammer.metrics.annotation.Timed;
import example.gettingstarted.Saying;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("hello")
@Produces(MediaType.APPLICATION_JSON)
public class AssetsResource {

    @GET
    @Timed
    public Saying hello() {
        return new Saying(1, "hello");
    }
}
AssetsHealthCheck.java
package example.core.assets;

import com.yammer.metrics.core.HealthCheck;

public class AssetsHealthCheck extends HealthCheck {

    public AssetsHealthCheck() {
        super("assets");
    }

    @Override
    protected Result check() throws Exception {
        return Result.healthy();
    }
}
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2