Configure dropwizard to server index.html for (almost) all routes?

牧云@^-^@ 提交于 2020-04-08 04:59:32

问题


I'm building a single page application which does all of it's html request routing on the client side and on the backend it uses dropwizard to provide a bunch of JSON services.

Essentially I'm having trouble getting the jetty in dropwizard to serve index.html for every request except to the following paths:

  /css
  /i18n
  /img
  /js
  /lib
  /services
  /templates

In fact I'm having a lot of trouble finding documentation that tells you how to setup any http routing at all. (I'm not a java guy).

Here's my simple yaml config:`

http:
  port: 8082
  adminPort: 8083
  rootPath: /service/*`

What do I need to add to acheive this.

Thanks


回答1:


I've done this without changing my configuration. In fact, it only took me one line of code, to be put in the initialize method of my Application class:

bootstrap.addBundle(new AssetsBundle("/app", "/", "index.html", "static"));

Which basically says to serve anything under /app inside my JAR file under the URL pattern /, with index.html as the default file. This bundle will be named static, but you could pick whatever name you like.

Note that I'm using version 0.7.0-rc2 of Dropwizard, I'm not sure whether it works for earlier versions as well.




回答2:


@mthmulders answer worked for me when I went to "/" and would work on other url's while the page had not reloaded, but would not work when I refreshed the page at "/foo/bar/bash" or any other url. I fixed this issue by mapping any 404 response to return back the index.html page instead.

Add your static assets to your initialization method of your Application class:

bootstrap.addBundle(new AssetsBundle("/app", "/", "index.html", "static"));

Add the mapping to your new 404 page to your run method of your Application class:

ErrorPageErrorHandler eph = new ErrorPageErrorHandler();
eph.addErrorPage(404, "/error/404");
environment.getApplicationContext().setErrorHandler(eph);

Add your resource that maps to /error/404

@GET
@Path("/error/404")
@Produces(MediaType.TEXT_HTML)
public Response error404() {
        // get html file from resources here...
        return Response.status(Response.Status.OK)
                .entity("<html>foo</html>")
                .build();
}

After doing this I was able to refresh the page at "/foo/bar/bash" and it still returned back the index.html file.



来源:https://stackoverflow.com/questions/22543007/configure-dropwizard-to-server-index-html-for-almost-all-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!