CSS file in Spring WAR returns 404

I have a Java EE application that I create using Spring and Maven. It has the usual project structure. Here is a little hierarchy.

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

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

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

When deploying the application, the CSS page is not located. When I look at the source of the page, the href value is /MyApplication/styles/main.css . Inside WAR there is /styles/main.css . However, I get 404 when I try to access the CSS file directly in the browser.

I found that the dispatch of dispatch servlets was the cause of this problem. The display is as follows.

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

I believe the dispatch servlet does not know how to handle the CSS request. What is the best way to deal with this problem? I would prefer not to change all my query mappings.

+4
source share
2 answers

You need to configure Spring to handle static resources (CSS, JS, images) separately from servlet requests for your application. To do this, configure the Spring configuration to map requests to static files through a separate top-level directory (for example, "static"):

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

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

Note. The convention dictates that you name your style directory "css".

+7
source

Add the following to 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 enable your css

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

Source: https://habr.com/ru/post/1433281/


All Articles