如何在Spring MVC中使用CDN

人气:566 发布:2022-10-16 标签: cdn java staticresource jsp spring-mvc

问题描述

我想在一个用Spring MVC创建的项目中使用CDN来提供静态内容,如CSS、JavaScript和图片。但我不知道怎么做。

我是Spring的新手,我在网上看到过一些帖子:

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

但他们没有解释如何实施。

例如:

过去,我使用<c:url>标签:

<img src="<c:url value="/path/to/image" />" alt="desc" />

当我使用CDN时,我可能会使用以下代码:

<img src="${env.cdnUrl}/mypath/pic.jpg" />

但是我应该把${env.cdnUrl}放在哪里(在web.xmldispatcher-servlet.xml(Spring MVC的配置)中)?如何在JSp中获取参数?

请帮帮我。谢谢。

推荐答案

我在Spring中实现了CDN服务,步骤如下:

dispatcher-servlet.xml(您的Spring配置)

中添加以下行
<util:properties id="propertyConfigurer" location="classpath:/app.properties"/>
<context:property-placeholder properties-ref="propertyConfigurer" />

当然,您需要在文件的顶部添加spring-util的DOM:

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"

安装位置app.properties

cdn.url=//cdn.domain.com/path/to/static/content

在JSP文件中使用CDN

<%@ 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" />

祝你好运!

787