详解springmvc拦截器拦截静态资源
|
springmvc拦截器interceptors springmvc拦截器能够对请求的资源路径进行拦截,极大的简化了拦截器的书写。但是,千万千万要注意一点:静态资源的放行。 上代码: <mvc:resources mapping="/resources/**" location="/static/resources" /> <mvc:resources mapping="/static/css/**" location="/static/css/" /> <mvc:resources mapping="/static/images/**" location="/static/images/" /> <mvc:resources mapping="/static/js/**" location="/static/js/" />
<mvc:interceptors>
<!-- 使用bean定义一个Interceptor,直接定义在mvc:interceptors根下面的Interceptor将拦截所有的请求
<bean class="com.myTree.interceptor.LoginInterceptor" />-->
<mvc:interceptor>
<mvc:mapping path="/**" />
<!-- 需排除拦截的地址 -->
<mvc:exclude-mapping path="/Login"/>
<mvc:exclude-mapping path="/login"/>
<mvc:exclude-mapping path="/sattic/**"/>
<!-- 定义在mvc:interceptor下面的表示是对特定的请求才进行拦截的 -->
<beans:bean class="com.myTree.interceptor.LoginInterceptor" >
</beans:bean>
</mvc:interceptor>
</mvc:interceptors>
问题来了,在请求jsp页面的时候,你的静态资源的访问仍然会被自定义拦截器拦截,这会导致程序运行的效率大大下降,还会不停的跳转到拦截器的逻辑。主要原因是 <mvc:mapping path="/**" /> 会对所有的请求资源进行拦截,虽然静态资源已经排除了,但还是会被拦截到。 如何解决这个bug呢? 主要有三种方式: 1、修改请求的url地址。 如果请求的url地址都是以*.do结尾,那么拦截器中的配置可以变为拦截以do结尾的资源,静态资源自然就不会被拦截到了;
<!-- 拦截器配置 -->
<mvc:interceptors>
<!-- session超时 -->
<mvc:interceptor>
<mvc:mapping path="/*/*"/>
<bean class="com.myTree.interceptor.LoginInterceptor">
<property name="allowUrls">
<list>
<!-- 如果请求中包含以下路径,则不进行拦截 -->
<value>/login</value>
<value>/js</value>
<value>/css</value>
<value>/image</value>
<value>/images</value>
</list>
</property>
</bean>
</mvc:interceptor>
</mvc:interceptors>
在拦截器中设定不拦截的属性:
/**
* 处理登录拦截器
*/
public class LoginInterceptor implements HandlerInterceptor{
public String[] allowUrls;//还没发现可以直接配置不拦截的资源,所以在代码里面来排除
public void setAllowUrls(String[] allowUrls) {
this.allowUrls = allowUrls;
}
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception {<pre name="code" class="java"> <span style="white-space:pre"> </span>String requestUrl = request.getRequestURI().replace(request.getContextPath(),"");
System.out.println(requestUrl);
if(null != allowUrls && allowUrls.length>=1){
for(String url : allowUrls) {
if(requestUrl.contains(url)) {
return true;
}
}
}
3、设置web.xml中的默认拦截器,不拦截静态资源 在springmvc的Dispatcher中配置<mvc:default-servlet-handler />(一般Web应用服务器默认的Servlet名称是"default",所以这里我们激活Tomcat的defaultServlet来处理静态文件,在web.xml里配置如下代码即可:) <!--该servlet为tomcat,jetty等容器提供,将静态资源映射从/改为/static/目录,如原来访问http://localhost/foo.css,现在http://localhost/static/foo.css --> <!-- 不拦截静态文件 --> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/js/*</url-pattern> <url-pattern>/css/*</url-pattern> <url-pattern>/images/*</url-pattern> <url-pattern>/fonts/*</url-pattern> </servlet-mapping> 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。 (编辑:哈尔滨站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
