Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Servlet - Mapping a servlet to every URL but a string

Tags:

java

servlets

I have a servlet configured to handle all URLs (*):

<servlet>
    <servlet-name>MyServ</servlet-name>
    <servlet-class>MyServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>MyServ</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

I need that for URLS beginning with /static/, it should serve them from the static WEB-INF. That is, MyServ should serve everything but /static.

How can I do that?


UPDATE: To clarify, what I'd like is:

/*/ - Goes to MyServ
/static/dir/file.css - Jetty serves the static file.css from the /dir/.

I'm not sure what web.xml to do, or where to put the static files.

I tried adding this:

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/static/*</url-pattern>
</servlet-mapping>

But, when I go to a /static/ URL, I just get:

HTTP ERROR 404

Problem accessing /static/dir/file.css. Reason: 
    Not Found

Powered by Jetty://

I'm not sure if my web.xml is wrong, or if I'm simply putting the files in the wrong place (I've tried under src/main/webapp and src/main/webapp/lib/META-INF/resources/)


Jetty

I am using Jetty. I want to avoid any other layers, such as Nginx, Apache, etc.

To win the bounty, please make sure you answer works for Jetty.

like image 334
SRobertJames Avatar asked Dec 11 '14 20:12

SRobertJames


1 Answers

Your best bet is probably to have a rule for static that occurs before the rule for *.

Rule for URL path mapping:

It is used in the following order. First successful match is used with no further attempts.

  1. The container will try to find an exact match of the path of the request to the path of the servlet. A successful match selects the servlet.
  2. The container will recursively try to match the longest path-prefix. This is done by stepping down the path tree a directory at a time, using the ’/’ character as a path separator. The longest match determines the servlet selected.
  3. If the last segment in the URL path contains an extension (e.g. .jsp), the servlet container will try to match a servlet that handles requests for the extension. An extension is defined as the part of the last segment after the last ’.’ character.
  4. If neither of the previous three rules result in a servlet match, the container will attempt to serve content appropriate for the resource requested. If a “default” servlet is defined for the application, it will be used.

So it will match the rule for /static/, and stop there.

like image 144
zebediah49 Avatar answered Oct 20 '22 21:10

zebediah49