在springmvc中<mvc:resources mapping="/static/**" location="/WEB-INF/static/"/> 定义了静态资源访问。
有时我们需要在程序中判断当前访问的是否是静态资源。下面我们来实现一个通用的方案。
一。首先在spring全局配置中定义
<bean id="resourceUrlProvider" class="org.springframework.web.servlet.resource.ResourceUrlProvider"/>
二。在springmvc的配置文件中 注册拦截器
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="org.springframework.web.servlet.resource.ResourceUrlProviderExposingInterceptor">
<constructor-arg>
<ref bean="resourceUrlProvider"/>
</constructor-arg>
</bean>
</mvc:interceptor>
</mvc:interceptors>
<mvc:resources location="xxxxx" mapping="xxxx"/> 等信息会注入到ResourceUrlProvider里。
三。定义一个通用获得bean实例的类
package org.jstudioframework.spring.utils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.NoSuchMessageException;
import java.util.Locale;
/**
* 在xml中配置bean,在程序中用来获取容器中的对象实例
*/
public class GenericUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext; // Spring应用上下文环境
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
GenericUtils.applicationContext = applicationContext;
}
/**
* 获取对象
*
* @param name
* @return Object 一个以所给名字注册的bean的实例
* @throws BeansException
*/
public static <T> T getBean(String name) throws BeansException {
return (T) applicationContext.getBean(name);
}
/**
* 获取类型为requiredType的对象
*
* @param clz
* @return
* @throws BeansException
*/
public static <T> T getBean(Class<T> clz) throws BeansException {
@SuppressWarnings("unchecked")
T result = (T) applicationContext.getBean(clz);
return result;
}
}
在spring全局配置中定义
<bean id="genericUtils" class="org.jstudioframework.spring.utils.GenericUtils"/>
四。定义一个判断是否是静态访问的工具类。
package org.jstudioframework.spring.web;
import org.jstudioframework.spring.utils.GenericUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.resource.ResourceUrlProvider;
import javax.servlet.http.HttpServletRequest;
/**
* Servlet工具类
*/
public class Servlets {
public static HttpServletRequest getRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
public static boolean isStaticFile(String uri) {
ResourceUrlProvider resourceUrlProvider = (ResourceUrlProvider) GenericUtils.getBean(ResourceUrlProvider.class);
String staticUri = resourceUrlProvider.getForLookupPath(uri);
return staticUri != null;
}
}