spring boot 简单拦截器,修改request的Parameter参数。

一、创建MyMvcConfig 继承WebMvcConfigurationSupport

 

package com.greattao.egtcp.web.foreign.util;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import javax.annotation.Resource;

@Configuration
public class MyMvcConfig extends WebMvcConfigurationSupport {

    @Resource
    private MyInterCeptor myInterCeptor;

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        // addPathPatterns("/**") 表示拦截所有的请求,
        // excludePathPatterns("/login", "/register") 表示除了登陆与注册之外,因为登陆注册不需要登陆也可以访问
        //注册自己的拦截器,并设置拦截路径,拦截多个可以全一个list集合
        registry.addInterceptor(myInterCeptor).addPathPatterns("/**").excludePathPatterns("/actuator/**","/login", "/index");
    }

    /**
     * 配置静态访问资源
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }


}

二、创建ParameterRequestWrapper 继承HttpServletRequestWrapper

package com.greattao.egtcp.web.foreign.util;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;

@Slf4j
public class ParameterRequestWrapper extends HttpServletRequestWrapper {



    private Map params = new HashMap<>();


    private Map mapCookies;

    /**
     * Constructs a request object wrapping the given request.
     *
     * @param request
     * @throws IllegalArgumentException if the request is null
     */
    public ParameterRequestWrapper(HttpServletRequest request) {
        super(request);
        //将参数表,赋予给当前的Map以便于持有request中的参数
        this.params.putAll(request.getParameterMap());
        this.mapCookies = new HashMap<>();
    }

    /**
     * 重载构造方法
     */

    public ParameterRequestWrapper(HttpServletRequest request, Map extendParams) {
        this(request);
        //这里将扩展参数写入参数表
        addAllParameters(extendParams);
    }

    /**
     * 在获取所有的参数名,必须重写此方法,否则对象中参数值映射不上
     *
     * @return
     */
    @Override
    public Enumeration getParameterNames() {
        return new Vector(params.keySet()).elements();
    }

    /**
     * 重写getParameter方法
     *
     * @param name 参数名
     * @return 返回参数值
     */
    @Override
    public String getParameter(String name) {
        String[] values = params.get(name);
        if (values == null || values.length == 0) {
            return null;
        }
        return values[0];
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] values = params.get(name);
        if (values == null || values.length == 0) {
            return null;
        }
        return values;
    }

    /**
     * 增加多个参数
     *
     * @param otherParams 增加的多个参数
     */
    public void addAllParameters(Map otherParams) {
        for (Map.Entry entry : otherParams.entrySet()) {
            addParameter(entry.getKey(), entry.getValue());
        }
    }

    /**
     * 增加参数
     *
     * @param name  参数名
     * @param value 参数值
     */
    public void addParameter(String name, Object value) {
        if (value != null) {
            if (value instanceof String[]) {
                params.put(name, (String[]) value);
            } else if (value instanceof String) {
                params.put(name, new String[]{(String) value});
            } else {
                params.put(name, new String[]{String.valueOf(value)});
            }
        }
    }

    /**
     * 本类 存入 Cookie
     * @return
     */
    public void putCookie(String name, String value) {
        this.mapCookies.put(name, value);
    }

    /**
     * 获取request中的cookie
     * @param key
     */
    public String getCookieForRequest(String key) {
        Cookie[] cookies = getCookieArrForRequest();
        if (cookies == null || cookies.length == 0) {
            return null;
        }
        List cookieList = new ArrayList<>(Arrays.asList(cookies));
        for (int i = 0; i < cookieList.size(); i++) {
            if(cookieList.get(i).getName().equals(key)){
                return cookieList.get(i).getValue();
            }
        }
        return null;
    }


    /**
     * 获取request中的cookie[]
     */
    public Cookie[] getCookieArrForRequest() {
        HttpServletRequest request = (HttpServletRequest) getRequest();
        return request.getCookies();
    }

    /**
     * 获取本类存放的和request中的Cookie
     * @return
     */
    public Cookie[] getCookies() {
        Cookie[] cookies = getCookieArrForRequest();
        if (mapCookies == null || mapCookies.isEmpty()) {
            return cookies;
        }
        if (cookies == null || cookies.length == 0) {
            List cookieList = new LinkedList<>();
            for (Map.Entry entry : mapCookies.entrySet()) {
                String key = entry.getKey();
                if (key != null && !"".equals(key)) {
                    cookieList.add(new Cookie(key, entry.getValue()));
                }
            }
            if (cookieList.isEmpty()) {
                return cookies;
            }
            return cookieList.toArray(new Cookie[cookieList.size()]);
        } else {
            List cookieList = new ArrayList<>(Arrays.asList(cookies));
            for (Map.Entry entry : mapCookies.entrySet()) {
                String key = entry.getKey();
                if (key != null && !"".equals(key)) {
                    for (int i = 0; i < cookieList.size(); i++) {
                        if(cookieList.get(i).getName().equals(key)){
                            cookieList.remove(i);
                        }
                    }
                    cookieList.add(new Cookie(key, entry.getValue()));
                }
            }
            return cookieList.toArray(new Cookie[cookieList.size()]);
        }
    }






}

三、创建MyInterCeptor实现HandlerInterceptor

package com.greattao.egtcp.web.foreign.util;

import com.cy.framework.util.storage.DataStorage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class MyInterCeptor implements HandlerInterceptor {

    /**
     * 过滤路径
     */
//    static final String AUTH_PATH = "/static/";
    private DataStorage dataStorage = DataStorage.getInstance();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String authToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsib2F1dGgyLXJlc291cmNlIiwiZWd0Y3AtY29udmVyZ2VuY2UiLCJlZ3RjcC1lbnF1aXJ5IiwiZWd0Y3Atc3lzIiwiZWd0Y3Atb2F1dGgyIiwiZWd0Y3AtdGFvQnV5ZXIiLCJlZ3RjcC1wcm9kdWN0IiwiZWd0Y3Atb3JkZXIiLCJlZ3RjcC1wdXJjaGFzZSIsImVndGNwLWludGVncmFsIiwiZWd0Y3AtY2hhbm5lbCIsImVndGNwLXZlcmlmbHkiLCJlZ3RjcC1zaG8iLCJlZ3RjcC1jb21tdW5pY2F0aW9uIiwiZWd0Y3AtdXNlciIsImF1dGgtY29udHJvbGxlciIsImVndGNwLW1hbmFnZXIiLCJlZ3RjcC1iZWhhdmlvciJdLCJ1c2VyX25hbWUiOiJjYWlnb3VzaGFuZ0BxcS5jb20iLCJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwiZXhwIjoyMjg5ODA5OTgwLCJhdXRob3JpdGllcyI6WyJSVUxFX0FETUlOIl0sImp0aSI6ImMwNzBjMjYzLWFjMGUtNDUwNC04NmM5LWFlOGJmMDUyNmMyNSIsImNsaWVudF9pZCI6ImFwcCJ9.WuB_z-OVuj28ITsodT9hqL4DoXTCYHkR61lUptcdkQE";
        ParameterRequestWrapper wrapper = new ParameterRequestWrapper(request);
        //TODO 上线注释放开
        String authToken=wrapper.getCookieForRequest(CommonParamt.TKOEN_NAME);
      if(StringUtils.isNotEmpty(authToken)){
            wrapper.addParameter(CommonParamt.TKOEN_NAME, "Bearer " + authToken);
            this.dataStorage.put("REQUEST_ATTRIBUTES", wrapper);
            return true;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }



}

 

 

你可能感兴趣的:(java)