【问题标题】:Spring mvc: css does not work when adding slash at the end of URLSpring mvc:在 URL 末尾添加斜杠时 css 不起作用
【发布时间】:2015-08-20 11:18:17
【问题描述】:

我是 Spring MVC 的新手,我遇到了 CSS 问题。当 URL 以斜杠结尾时,CSS 不起作用。
链接是这样的
<link rel="stylesheet" href="themes/style.css">
mvc:资源映射
<mvc:resources mapping="/themes/**" location="/WEB-INF/themes/"/>
requestMapping 是这样的

@RequestMapping("/login")
public ModelAndView loginPage() {

    ModelAndView model = new ModelAndView("login");

    return model;
}

所以问题是当我输入像 ../login 这样的 URL 时,css 会正常加载,但是当我输入带有斜杠的 ../login/ 时,css 不会加载。 好吧,这里有很多类似的问题,但没有一个是针对 Spring MVC 的。

【问题讨论】:

    标签: css spring spring-mvc url


    【解决方案1】:

    代替

    <link rel="stylesheet" href="themes/style.css">
    

    试试这个:

    <link rel="stylesheet" href="/themes/style.css">
    

    当您使用href="themes/style.css" 时,对于像:.../login/ 这样的 url,css 文件的请求 url 看起来像:

    .../login/themes/style.css
    

    这是不正确的。当您使用href="/themes/style.css" 时,它总是会导致:

    .../themes/style.css
    

    更新:

    如果是jsp页面,则添加 &lt;%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %&gt; 在页面顶部 并改变:

    <link rel="stylesheet" href="themes/style.css">
    

    进入

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

    【讨论】:

    • 在这种情况下,../login 的 CSS 也会停止加载。
    【解决方案2】:

    它会 100% 工作

    第一步

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

    设置 2

    <spring:url var="css" value="/resources/css/"/>
    <spring:url var="js" value="/resources/js/"/>
    
    <spring:url var="image" value="/resources/image/"/> 
    

    在值后添加一个斜杠

    第三步

    像这样添加你的样式表

     <link rel="stylesheet" 
        href="${css}/common/bootstrap.min.css">
    

    【讨论】:

      猜你喜欢
      • 2013-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      • 2017-05-05
      • 2014-09-23
      • 2016-03-27
      • 1970-01-01
      相关资源
      最近更新 更多