Issue
I want to use CDN to serve static content like CSS, JavaScript and images in a project created with Spring MVC. But I didn't how to do it.
I'm new to Spring and I have seen some posts on the web:
- href="https://stackoverflow.com/questions/18915975/jsp-spring-mvc-and-cdn">JSP/Spring MVC and CDN?
- How to use property from property file specified in PropertyPlaceholderConfigurer in JSP
- How to show values from property file in JSP in a spring MVC app
- http://tshikatshikaaa.blogspot.com/2012/11/serving-static-resources-with-spring-mvc.html
But they didn't explain how to implement it.
For example:
In the past, I use <c:url>
tags:
<img src="<c:url value="/path/to/image" />" alt="desc" />
When I use CDN, I may use following code:
<img src="${env.cdnUrl}/mypath/pic.jpg" />
But where should I put ${env.cdnUrl}
(in web.xml
or dispatcher-servlet.xml
(the configuration of Spring MVC))? And how to get the parameter in JSP?
Please help me. Thanks.
Solution
I implemented CDN service in Spring using following steps:
Add following lines in dispatcher-servlet.xml
(Your Spring Configuration)
<util:properties id="propertyConfigurer" location="classpath:/app.properties"/>
<context:property-placeholder properties-ref="propertyConfigurer" />
Of course, you need to add DOM for spring-util
at the top of the file:
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.1.xsd"
Setup in app.properties
cdn.url=//cdn.domain.com/path/to/static/content
Use CDN in JSP files
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<spring:eval expression="@propertyConfigurer.getProperty('cdn.url')" var="cdnUrl" />
<link rel="stylesheet" type="text/css" href="${cdnUrl}/css/semantic.min.css" />
<link rel="stylesheet" type="text/css" href="${cdnUrl}/css/font-awesome.min.css" />
Good luck!
Answered By - Haozhe Xie
Answer Checked By - Pedro (JavaFixing Volunteer)