Jersey /* Servlet 映射觸發靜態資源的404 錯誤
如果Jersey 的URL 模式在Jersey 2.0 版本中映射到//*則對於所有靜態資源(例如index.html),可能會導致404 錯誤。以下是導致此問題的web.xml 配置:
<code class="xml"><servlet> <servlet-name>JerseyApp</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <init-param> <param-name>javax.ws.rs.Application</param-name> <param-value>org.frog.jump.JerseyApp</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>JerseyApp</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping></code>
Jersey 1.x 的解決方案
在Jersey 1.x 中,您可以從Jersey servlet 切換加入過濾器以啟用靜態內容服務:
<code class="xml"><filter> <filter-name>Jersey Filter</filter-name> <filter-class>com.sun.jersey.spi.container.servlet.ServletContainer</filter-class> <init-param> <param-name>javax.ws.rs.Application</param-name> <param-value>org.frog.jump.JerseyApp</param-value> </init-param> <init-param> <param-name>com.sun.jersey.config.property.WebPageContentRegex</param-name> <param-value>/.*html</param-value> </init-param> </filter> <filter-mapping> <filter-name>Jersey Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping></code>
Jersey 2.x 的解決方案
在Jersey 2.x 中,使用以下過濾器配置:
<code class="xml"><filter> <filter-name>Jersey Filter</filter-name> <filter-class>org.glassfish.jersey.servlet.ServletContainer</filter-class> <init-param> <param-name>jersey.config.server.provider.packages</param-name> <param-value>org.example</param-value> </init-param> <init-param> <param-name>jersey.config.servlet.filter.staticContentRegex</param-name> <param-value>/.*html</param-value> </init-param> </filter> <filter-mapping> <filter-name>Jersey Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping></code>
確保您的POM 包含:
<code class="xml"><dependency> <groupId>org.glassfish.jersey.core</groupId> <artifactId>jersey-server</artifactId> <version>${jersey2.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.glassfish.jersey.containers</groupId> <artifactId>jersey-container-servlet-core</artifactId> <version>${jersey2.version}</version> <type>jar</type> <scope>compile</scope> </dependency></code>
如果提供不同的靜態檔案類型(例如CSS、JSP),請自訂init-param 中的正規則表達式。
以上是為什麼將 Jersey 的 URL 模式對應到 /* 會導致 Jersey 2.0 中的靜態資源出現 404 錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!