das_j
das_j

Reputation: 4794

Serving static resources, via default servlet, in Jetty

My Servlet (running on Jetty) should also deploy static content that is in the static directory.

Directory structure:

/
  - static/
    - [static files]
  - WEB-INF/
    - [my servlet .class files and the web.xml]

My web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">

    <filter>
        <filter-name>filter</filter-name>
        <filter-class>com.example.StaticFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

My main Servlet file:

@WebServlet("/*")
public class SampleClass extends HttpServlet {
     //Code
}

And my filter:

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class StaticFilter implements Filter {

    @Override
    public void init(FilterConfig fc) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String path = req.getRequestURI().substring(req.getContextPath().length());

        if (path.startsWith("/static")) {
            request.getRequestDispatcher(path).forward(request, response);
        } else {
            chain.doFilter(request, response);
        }
    }
}

Now, if I call /static/style.css, I want to get the file from /static and not be redirected to the servlet.

Server: Jetty 9.1.0 RC1

Upvotes: 3

Views: 3448

Answers (1)

Joakim Erdfelt
Joakim Erdfelt

Reputation: 49462

Your @WebServlet defined at PathSpec of "/*" is preventing the default servlet from ever being executed.

You essentially said, "I know what I'm doing, I want all requests, for all paths, to route through me"

Consider setting up your Servlet at pathspec of "/sample", or "/sample/*", or something similar. Anything but "/" or "/*" as that will catch everything.

@WebServlet("/sample/*")

Otherwise, you can reference the default servlet in any container, not just Jetty (its a mandatory feature of the Servlet Spec) like this ...

getServletContext().getNamedDispatcher("default").forward(request, response);

Upvotes: 2

Related Questions