Spring mvc: css does not work when adding slash at the end of URL

大兔子大兔子 提交于 2020-01-04 15:27:44

问题


I am new to Spring MVC and i am having a problem with CSS. When the URL ends with slash CSS does not work.
link goes like this
<link rel="stylesheet" href="themes/style.css">
mvc:resources mapping
<mvc:resources mapping="/themes/**" location="/WEB-INF/themes/"/>
and requestMapping goes like this

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

    ModelAndView model = new ModelAndView("login");

    return model;
}

So the problem is when i enter a URL like ../login the css loads normally, but when i enter ../login/ with ending slash, then the css does not load. Well there are many similar questions in here, but none of them is for Spring MVC.


回答1:


Instead of

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

try this:

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

When you use href="themes/style.css" then for url like: .../login/ the request url for css file looks like:

.../login/themes/style.css

which is incorrect. When you use href="/themes/style.css" then it always should result with:

.../themes/style.css

Update:

If it is jsp page, then add <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> on top of the page and change:

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

into

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



回答2:


it will work 100%

step 1

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

setp 2

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

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

add a slash after value

step 3

add your style sheet like this

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


来源:https://stackoverflow.com/questions/32116829/spring-mvc-css-does-not-work-when-adding-slash-at-the-end-of-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!