【问题标题】:Serving static content with Spring使用 Spring 提供静态内容
【发布时间】:2016-09-26 09:27:22
【问题描述】:

我一直在关注一些关于使用 Spring 提供静态文件(CSS、JS 等)的教程,据我所知,我应该能够看到我的静态文件,但我不能。

我的spring-web-servlet.xml 看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="brass.ducks" />

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <mvc:resources mapping="/styles/**" location="views" />
    <mvc:annotation-driven/>

</beans>

最后一行建议styles/whatever.css 后面的任何 URL 都应查看我的视图文件夹并从那里提供服务。例如,我的页面有一个样式表链接为/styles/css/bootstrap.min.css(将完成到http://localhost:8080/Brass-Ducks/styles/css/bootstrap.min.css),但这并不能解析为我的样式表。

我的文件夹层次结构如下所示:

我错过了什么吗?

编辑

按照建议,我提取了我的 .war 文件,发现文件夹层次结构如下所示:

我已将web.xml 修改为如下所示:

<mvc:resources mapping="/styles/**" location="/WEB-INF/views/" />
<mvc:annotation-driven/>

但 URL http://localhost:8080/Brass-Ducks/styles/css/bootstrap.min.css 仍然无法解析 CSS 文件。

【问题讨论】:

    标签: spring spring-mvc


    【解决方案1】:

    将您的 styles 目录移动到 /webapp/resourses 路径。所以你会有/webapp/resourses/styles。使用&lt;mvc:resources mapping="/styles/**" location="/resources/styles/" 更改xml 配置并尝试从http://localhost:8080/Brass-Ducks/styles/css/bootstrap.min.css 获取

    【讨论】:

      【解决方案2】:

      将映射配置更改为:

      <mvc:resources mapping="/styles/**" location="/WEB-INF/views/styles/" />
      

      【讨论】:

        【解决方案3】:

        是的,您缺少/,它应该是这样的:

        <mvc:resources mapping="/styles/**" location="/views/" />
        

        而xml配置spring并不是一个好主意,试试java config..

        【讨论】:

        • http://localhost:8080/Brass-Ducks/styles/css/bootstrap.min.css 仍然没有显示样式表。
        • @Nanor 使用文件浏览器打开您的war 文件,检查是否存在。回复是404?
        • 我可以在我的文件浏览器中看到我的.war 文件,但我不明白你的意思。
        • @Nanor 检查响应是否为404,提取你的war文件并查看资源是否在正确的路径中
        猜你喜欢
        • 2011-10-14
        • 2019-10-20
        • 2011-03-13
        • 2011-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-26
        • 2016-07-14
        相关资源
        最近更新 更多