Spring mvc 拦截器

1.xml配置




  

2.java拦截器编写

创建路径


image.png
package com.xxx.unionpay.intercerptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class UnionPayIntercerptor implements HandlerInterceptor {
    private final static Logger log = LoggerFactory.getLogger("UnionPayIntercerptor");

    private List excludedUrls;
    public List getExcludedUrls() {  return excludedUrls; }
    public void setExcludedUrls(List excludedUrls) { this.excludedUrls = excludedUrls; }

    /**
     * 返回值:表示是否需要将当前请求拦截
     * true: 请求继续运行
     * false:请求被终止
     * o:    表示被拦截的请求目标对象
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //判断请求是否需要使用该拦截器,在spring_mvc配置里面
        String requestUri = httpServletRequest.getRequestURI();
        for (String url : excludedUrls){
            if (requestUri.endsWith(url)){
                return true;
            }
        }

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        //可通过modelAndView参数改变现实的视图,或修改发往视图的方法
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

3.注册拦截器




    
        
            
            
                
                    
                        xxx/v1.0/xxx/xxx.fgl
                        xxx/v1.0/xxx/xxx.fgl
                        xxx/v1.0/xxx/xxx.fgl
                        xxx/v1.0/xxx/xxx.fgl
                        xxx/v1.0/xxx/xxx.fgl
                        xxx/v1.0/xxx/xxx.fgl
                    
                
            
        
    
    

你可能感兴趣的:(Spring mvc 拦截器)