Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS file in a Spring WAR returns a 404

Tags:

html

css

jsp

maven

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.

like image 487
Snowy Coder Girl Avatar asked Dec 21 '22 16:12

Snowy Coder Girl


1 Answers

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".

like image 106
nickdos Avatar answered Jan 04 '23 05:01

nickdos