How to use CDN in Spring MVC

Haozhe Xie picture Haozhe Xie · Feb 26, 2015 · Viewed 8.1k times · Source

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:

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.

Answer

Haozhe Xie picture Haozhe Xie · Mar 2, 2015

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!