Use CDN Service in Spring MVC

A few days ago, I created TestZilla on Aliyun Elastic Compute Service.

However, with the increment of PV, I decided to use CDN to caches static files(images, css and javascripts).

But there's no one told me how to use CDN with Spring MVC, so I asked a question on StackOverflow.

Setup Spring Configuration

First of all, you need to use PropertyPlaceholderConfigurer in Spring Configuration(such as dispatcher-servlet.xml)

<!-- Property File Location -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	<property name="locations">
		<list>
			<value>classpath:/testzilla.properties</value>
		</list>
	</property>
</bean>
<util:properties id="propertyConfigurer" location="classpath:/testzilla.properties"/>
<context:property-placeholder properties-ref="propertyConfigurer" />

Of course, you need to add XML Namespaces:

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
	http://www.springframework.org/schema/util 
	http://www.springframework.org/schema/util/spring-util-4.1.xsd">
</beans>

Create Properties File

As I was declared in the Spring Configuration, there's a testzilla.properties in classpath.
You need to create the file and add following lines in it:

cdn.url=//cdn.testzilla.org/

Of course, you can add extra properties if needed:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/testzilla?characterEncoding=UTF-8
jdbc.username=root
jdbc.password=

Use CDN Property in JSP

Now, we can get the URL of CDN in JSP as following:

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<spring:eval expression="@propertyConfigurer.getProperty('cdn.url')" var="cdnUrl" />
<!DOCTYPE html>
<html lang="${language}">
<head>
    <meta charset="UTF-8">
    <title>Home | TestZilla</title>
    <link rel="stylesheet" type="text/css" href="${cdnUrl}/css/semantic.min.css" />
</head>
</html>

Reference

  • http://stackoverflow.com/questions/18915975/jsp-spring-mvc-and-cdn
  • http://stackoverflow.com/questions/3933862/how-to-use-property-from-property-file-specified-in-propertyplaceholderconfigure
  • http://stackoverflow.com/questions/15111260/how-to-show-values-from-property-file-in-jsp-in-a-spring-mvc-app
  • http://www.mytechnotes.biz/2012/11/serving-static-resources-with-spring-mvc.html

 

 

Contact Us
  • Room 614, Zonghe Building, Harbin Institute of Technology
  • cshzxie [at] gmail.com