0
点赞
收藏
分享

微信扫一扫

springMVC拦截器interceptor(如何释放静态资源)

快乐码农Alan007 2022-04-01 阅读 135
java

xml文件配置了interceptor拦截器和静态资源释放

<mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.itheima.interceptor.xxx" >
             
            </bean>
        </mvc:interceptor>
    </mvc:interceptors>

<!--    3 静态资源权限开放-->
    <mvc:default-servlet-handler ></mvc:default-servlet-handler>

 排除要拦截的资源

<mvc:interceptors>
	<!-- 使用bean定义一个Interceptor,直接定义在mvc:interceptors根下面的Interceptor将拦截所有的请求 
	<bean class="com.itheima.interceptor.PrivilegeInterceptor" />-->
	<mvc:interceptor>
		 <mvc:mapping path="/**" />
		 <!-- 需排除拦截的地址 -->  
         <mvc:exclude-mapping path="/Login"/>  
         <mvc:exclude-mapping path="/img"/>  
         <mvc:exclude-mapping path="/css/*"/> 
         <mvc:exclude-mapping path="/js/*"/>   
		 <!-- 定义在mvc:interceptor下面的表示是对特定的请求才进行拦截的 -->
		 <beans:bean class="com.itheima.interceptor.PrivilegeInterceptor" />
	</mvc:interceptor>
</mvc:interceptors>

这时会发现静态资源还是不能加载出来。

这时我们进行代码深度剖析。xml文件这样修改,在拦截器中注入需要释放的静态资源

 <!--    配置拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.itheima.interceptor.PrivilegeInterceptor" >
<!--                在拦截器PrivilegeInterceptor中设置一个数组,存放要释放的静态资源的路径-->
                <property name="allowUrls">
                    <list>
                        <!-- 如果请求中包含以下路径,则不进行拦截 -->
                        <value>/login.jsp</value>
                        <value>/css</value>
                        <value>pages</value>
                        <value>/img</value>
                        <value>/plugins</value>
                    </list>
                </property>
            </bean>
        </mvc:interceptor>
    </mvc:interceptors>

 拦截器preHandle()方法中进行方法增强,利用的就是AOP的思想,直接照般过去就可以了

 //还没发现可以直接配置不拦截的资源,所以在代码里面来排除
    public String[] allowUrls;
    public void setAllowUrls( String []allowUrls) {
        this.allowUrls = allowUrls;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //对静态资源放行
        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;
                }
            }
        }
举报

相关推荐

0 条评论