Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving static files with Jersey 2

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

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.

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?

Here is my 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>
like image 693
mbcrute Avatar asked Nov 05 '14 17:11

mbcrute


People also ask

How are static files served?

To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express. The root argument specifies the root directory from which to serve static assets.

Can Tomcat serve static files?

Tomcat will serve any static content from a WAR file using the DefaultServlet.


1 Answers

I was pointed to this question 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.

like image 145
mbcrute Avatar answered Sep 28 '22 06:09

mbcrute