我想使用CDN在使用Spring MVC创建的项目中提供CSS,JavaScript和图像等静态内容。但我不知道怎么做。
我是Spring的新手,我在网上看过一些帖子:
但他们没有解释如何实施它。
例如:
过去,我使用<c:url>
代码:
<img src="<c:url value="/path/to/image" />" alt="desc" />
当我使用CDN时,我可以使用以下代码:
<img src="${env.cdnUrl}/mypath/pic.jpg" />
但是我应该在哪里放${env.cdnUrl}
(在web.xml
或dispatcher-servlet.xml
(Spring MVC的配置))?以及如何在JSP中获取参数?
请帮帮我。感谢。
答案 0 :(得分:3)
我使用以下步骤在Spring中实现了CDN服务:
在dispatcher-servlet.xml
(您的春季配置)中添加以下行
<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" />
祝你好运!
答案 1 :(得分:0)
方法:
将env值写入属性文件并尝试在jsp页面中访问它。如果使用InternalResourceViewResolver,那么exposedContextBeanNames可以帮助在jsp中公开属性。
<bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list><value>property_file</value></list>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
<property name="exposeContextBeansAsAttributes" value="true"/>
<property name="exposedContextBeanNames">
<list>
<value>properties</value>
</list>
</property>
</bean>
并以$ {properties.env}
的形式访问jsp中的值答案 2 :(得分:0)
您也可以通过拦截器实现此目的。
<mvc:interceptors>
<!-- path interceptor adds servlet path as an attribute -->
<bean class="com.test.myInterceptor" />
然后在拦截器代码中,您可以设置属性
@Override
public boolean preHandle(final HttpServletRequest request,
final HttpServletResponse response,
final Object handler) {
// set the attribute for URL