javahtmlspring-mvc

Spring MVC absolute URL problem


Background

I am developing an application (with Spring MVC) with its base path as:

http://localhost:8080/myapplication/

I have a stylesheet /css/style.css that I am trying to refer with absolute path in a JSP as:

<link rel="stylesheet" href="/css/style.css" type="text/css" media="screen, projection">

Problem

The stylesheet never loads in the browser. When I follow the stylesheet link through browser's view source feature, the link appears to be:

http://localhost:8080/css/style.css

Which should have had been:

http://localhost:8080/myapplication/css/style.css

I used to fix this issue with html:rewrite tag while working with Struts. Is there any equivalent tag/technique in Spring MVC?

Thanks for your time.


Solution

  • Use the JSTL c:url tag.

    <c:url value="/css/style.css" var="url" />
    <link rel="stylesheet" href="${url}" type="text/css" media="screen, projection">
    

    You can also use the pageContext to prefix the context path.

    <link rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css" type="text/css" media="screen, projection">