CSS file in a Spring WAR returns a 404

后端 未结 2 1168
感情败类
感情败类 2021-01-19 17:18

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
             


        
相关标签:
2条回答
  • 2021-01-19 17:57

    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">
    
    0 讨论(0)
  • 2021-01-19 18:13

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

    0 讨论(0)
提交回复
热议问题