java 使用 Jersey 2 提供静态文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26763039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:32:51  来源:igfitidea点击:

Serving static files with Jersey 2

javaservletsjerseyjersey-2.0

提问by mbcrute

I'm new to Jersey and servlets in general so hopefully I'm just missing something simple...

我是泽西岛和 servlets 的新手,所以希望我只是错过了一些简单的东西......

I've got a Jersey app (v2.13) up and running using Guice (3.0) for dependency injection along with some static files in src/main/webapp. If I map my Jersey servlet to anything other than /* and make a request for a static file in the webapp folder, it gets served up no problem. If I map my Jersey servlet to the root, any request for a static file is met with a 404.

我有一个 Jersey 应用程序 (v2.13) 启动并运行,使用 Guice (3.0) 进行依赖注入以及 src/main/webapp 中的一些静态文件。如果我将 Jersey servlet 映射到 /* 以外的任何内容,并请求 webapp 文件夹中的静态文件,则它不会出现问题。如果我将 Jersey servlet 映射到根目录,则任何对静态文件的请求都会遇到 404。

I'd really prefer to have the Jersey servlet mapped to the root but I also need to be able to serve static content. Is there any way to accomplish this? Perhaps to map the Jersey servlet to the root but ignore requests for /assets/* or something similar?

我真的更喜欢将 Jersey servlet 映射到根目录,但我还需要能够提供静态内容。有什么办法可以做到这一点吗?也许将 Jersey servlet 映射到根目录,但忽略对 /assets/* 或类似内容的请求?

Here is my web.xml:

这是我的 web.xml:

<filter>
    <filter-name>guice-filter</filter-name>
    <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>guice-filter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<listener>
    <listener-class>com.example.MyGuiceServletContextListener</listener-class>
</listener>

<servlet>
    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>com.example.MyResourceConfig</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Jersey Web Application</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

采纳答案by mbcrute

I was pointed to thisquestion and got my answer. Basically I just need to change the Jersey servlet to a filter and supply a static content regex as an init param. Now I have my servlet mounted at the root and my static files are getting served up just like I wanted.

我被指向这个问题并得到了我的答案。基本上我只需要将 Jersey servlet 更改为过滤器并提供静态内容正则表达式作为 init 参数。现在我将我的 servlet 安装在根目录下,并且我的静态文件正像我想要的那样提供服务。