详解springmvc拦截器拦截静态资源
springmvc拦截器interceptors
springmvc拦截器能够对请求的资源路径进行拦截,极大的简化了拦截器的书写。但是,千万千万要注意一点:静态资源的放行。
上代码:
<mvc:resourcesmapping="/resources/**"location="/static/resources"/> <mvc:resourcesmapping="/static/css/**"location="/static/css/"/> <mvc:resourcesmapping="/static/images/**"location="/static/images/"/> <mvc:resourcesmapping="/static/js/**"location="/static/js/"/>
<mvc:interceptors> <!--使用bean定义一个Interceptor,直接定义在mvc:interceptors根下面的Interceptor将拦截所有的请求 <beanclass="com.myTree.interceptor.LoginInterceptor"/>--> <mvc:interceptor> <mvc:mappingpath="/**"/> <!--需排除拦截的地址--> <mvc:exclude-mappingpath="/Login"/> <mvc:exclude-mappingpath="/login"/> <mvc:exclude-mappingpath="/sattic/**"/> <!--定义在mvc:interceptor下面的表示是对特定的请求才进行拦截的--> <beans:beanclass="com.myTree.interceptor.LoginInterceptor"> </beans:bean> </mvc:interceptor> </mvc:interceptors>
问题来了,在请求jsp页面的时候,你的静态资源的访问仍然会被自定义拦截器拦截,这会导致程序运行的效率大大下降,还会不停的跳转到拦截器的逻辑。主要原因是
<mvc:mappingpath="/**"/>
会对所有的请求资源进行拦截,虽然静态资源已经排除了,但还是会被拦截到。
如何解决这个bug呢?
主要有三种方式:
1、修改请求的url地址。
如果请求的url地址都是以*.do结尾,那么拦截器中的配置可以变为拦截以do结尾的资源,静态资源自然就不会被拦截到了;
2、在自定义拦截器中对资源进行判断,如果满足需要排除的资源,就进行放行。
<!--拦截器配置--> <mvc:interceptors> <!--session超时--> <mvc:interceptor> <mvc:mappingpath="/*/*"/> <beanclass="com.myTree.interceptor.LoginInterceptor"> <propertyname="allowUrls"> <list> <!--如果请求中包含以下路径,则不进行拦截--> <value>/login</value> <value>/js</value> <value>/css</value> <value>/image</value> <value>/images</value> </list> </property> </bean> </mvc:interceptor> </mvc:interceptors>
在拦截器中设定不拦截的属性:
/** *处理登录拦截器 */ publicclassLoginInterceptorimplementsHandlerInterceptor{ publicString[]allowUrls;//还没发现可以直接配置不拦截的资源,所以在代码里面来排除 publicvoidsetAllowUrls(String[]allowUrls){ this.allowUrls=allowUrls; } @Override publicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse, Objecthandler)throwsException{<prename="code"class="java"><spanstyle="white-space:pre"></span>StringrequestUrl=request.getRequestURI().replace(request.getContextPath(),""); System.out.println(requestUrl); if(null!=allowUrls&&allowUrls.length>=1){ for(Stringurl:allowUrls){ if(requestUrl.contains(url)){ returntrue; } } }
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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。