How to serve static content with JAX-RS?

做~自己de王妃 提交于 2019-12-03 05:19:17

Just found it.

According to the javax.ws.rs.Path annotation javadocs one can specify a regex to indicate what is considered to be the template parameter match.

Hence, the following code works:

@Path("static")
public class StaticContentHandler {
  ...
  @GET
  @Path("{path:.*}")
  public FileRepresentation Get(@PathParam("path") String path) {
    ...;
  }
}

GET http://localhost:8182/static/yaba/daba/doo.png reaches the Get method with path equal to "yaba/daba/doo.png" - just what I was looking for.

Hope it helps anyone.

BTW, FileRepresentation belongs to Restlet, so a really pure JAX-RS implementation would return something else here.

Assuming that static folder is located here: ./src/main/resources/WEB-INF/static in your project:

@Path("")
public class StaticResourcesResource {

  @Inject ServletContext context;

  @GET
  @Path("{path: ^static\\/.*}")
  public Response staticResources(@PathParam("path") final String path) {

    InputStream resource = context.getResourceAsStream(String.format("/WEB-INF/%s", path));

    return Objects.isNull(resource)
        ? Response.status(NOT_FOUND).build()
        : Response.ok().entity(resource).build();
  }
}

Here is full description with how-to example and repository: https://daggerok.github.io/thymeleaf-ee/#configure-jax-rs-serve-static-files-and-webjars

You can do it with pure JAX-RS by implementing the corresponding resources: basically you just need to send a byte array and JAX-RS already includes the Byte Array provider for any media type.

The problem that your implementation will probably be less efficient then standard implementations of web servers. Usually the best is to put the static content on a Web Server like Apache HTTPD or IIS or even Tomcat.

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