【问题标题】:Spring MVC. Why resources are not visible from JSP page?春天MVC。为什么资源在 JSP 页面中不可见?
【发布时间】:2018-10-11 07:49:05
【问题描述】:

我有简单的 spring mvc 应用程序。我尝试将 CSS 之类的静态资源添加到我的应用程序中,但我的 jsp 页面找不到它。

我的 jsp 页面如下所示:

    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title><fmt:message key="app.title"/></title>
        <link rel="stylesheet" href="/resources/css/style.css">
    </head>
    <body>
         ..................................................................
    </body>
    </html>

我的 spring-mvc 上下文也是这样:

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns="http://www.springframework.org/schema/beans"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
   http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<mvc:annotation-driven/>

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

<context:component-scan base-package="ru.javawebinar.**.web"/>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:viewClass="org.springframework.web.servlet.view.JstlView"
      p:prefix="/WEB-INF/jsp/"
      p:suffix=".jsp"/>

我的资源位于:

【问题讨论】:

  • 请将代码发布为代码而不是图像。
  • 你用什么 URL 打开你的 JSP 页面?我认为它应该是一个相对或绝对路径问题。

标签: java spring spring-mvc


【解决方案1】:

你在使用 JSTL 吗?如果是这样,您可以像这样包含。

 <link href="<c:url value="/resources/css/style.css" />" rel="stylesheet">

另一种方法是:

<link href="${pageContext.request.contextPath}/resources/css/style.css" rel="stylesheet" >

【讨论】:

    【解决方案2】:

    试试这些改变:

    在spring-web-config.xml中:

    <mvc:resources mapping="/resources/**" location="/resources/css/"/>
    

    在你的jsp文件中:

    <link href="<c:url value="/resources/css/style.css" />" rel="stylesheet">
    

    更新:

    对于 Spring,您可以在 *.jsp 文件中尝试:

    <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title><fmt:message key="app.title"/></title>
        <spring:url value="/resources/css/style.css" var="mainCss" />
        <link href="${mainCss}" rel="stylesheet" />
      </head>
      <body>
        ..................................................................
      </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-02
      • 1970-01-01
      • 1970-01-01
      • 2016-07-12
      • 2017-08-02
      相关资源
      最近更新 更多