Spring文件中的CSS文件返回404 [英] CSS file in a Spring WAR returns a 404

查看:435
本文介绍了Spring文件中的CSS文件返回404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java EE应用程序,我正在使用Spring和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

我想在我的JSP中包含这个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}">

部署应用程序时,未找到CSS页面。当我查看页面源代码时,href是 /MyApplication/styles/main.css 。查看WAR内部,有一个 /styles/main.css 。但是,当我尝试直接在浏览器中访问CSS文件时,我得到了一个404。

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.

我发现问题的原因是Dispatcher Servlet映射。映射如下所示。

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>



我想象Dispatcher Servlet不知道如何处理CSS请求。处理这个问题的最佳方法是什么?我宁愿不必改变我所有的请求映射。

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.

推荐答案

您需要配置Spring来处理静态资源(CSS,JS,图像)。为此,请配置您的Spring配置,通过单独的顶级目录(例如静态)将请求映射到静态文件:

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="/" />

然后更改您的JSP以使用路径 / static / styles / main。 css

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

请注意,约定规定您将styles目录命名为css。

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

这篇关于Spring文件中的CSS文件返回404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆