Snowy Coder Girl
Snowy Coder Girl

Reputation: 5518

CSS file in a Spring WAR returns a 404

I have a Java EE application that I am building with Spring and Maven. It has the usual project structure. Here is a bit of the hierarchy.

MyApplication
    src
        main
            webapp
                WEB-INF
                    layout
                        header.jsp
                styles
                    main.css

I want to include that CSS file in my JSP. I have the following tag in place.

<c:url var="styleSheetUrl" value="/styles/main.css" />
<link rel="stylesheet" href="${styleSheetUrl}">

When I deploy the application, the CSS page isn't being located. When I view the page source, the href is /MyApplication/styles/main.css. Looking inside the WAR, there is a /styles/main.css. However, I get a 404 when I try to access the CSS file directly in the browser.

I discovered that the reason for the issue was the Dispatcher Servlet mapping. The mapping looks as follows.

<servlet-mapping>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

I imagine the Dispatcher Servlet doesn't know how to handle the CSS request. What is the best way to handle this issue? I would rather not have to change all of my request mappings.

Upvotes: 4

Views: 6420

Answers (2)

shammerw0w
shammerw0w

Reputation: 1986

Add the following in web.xml

<servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.js</url-pattern>
</servlet-mapping>

and use the following to include your css

<link rel="stylesheet" href="styles/main.css">

Upvotes: 4

nickdos
nickdos

Reputation: 8414

You need to configure Spring to handle the static resources (CSS, JS, images) separately from servlet requests to your app. To do this, configure your Spring config to map requests to static files via a separate top level directory (e.g. "static"):

<!-- Where to load static resources (css, js, images) -->
<mvc:resources mapping="/static/**" location="/" />

Then change your JSP to use the path /static/styles/main.css.

Note, convention dictates you name your "styles" directory to "css".

Upvotes: 7

Related Questions