在Fliter中 基于HttpServletRequest 创建SafeboxRequestWrapper对象,然后把SafeboxRequestWrapper对象作为HttpServletRequest传递下去



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;
/**
 * HttpServletRequest包装类,用于在filter中增删改请求参数和header
 * @author sola
 * */
public class SafeboxRequestWrapper extends HttpServletRequestWrapper {

    public SafeboxRequestWrapper(HttpServletRequest request) {
        super(request);
        //将参数表,赋予给当前的Map以便于持有request中的参数
        this.params.putAll(request.getParameterMap());
    }

    private Map<String, String> headerMap = new HashMap<String, String>();
    private Map<String , String[]> params = new HashMap<String, String[]>();

    public void addHeader(String name, String value) {
        headerMap.put(name, value);
    }

    @Override
    public String getHeader(String name) {
        String headerValue = super.getHeader(name);
        if (headerMap.containsKey(name)) {
            headerValue = headerMap.get(name);
        }
        return headerValue;
    }

    @Override
    public Enumeration<String> getHeaderNames() {
        List<String> names = Collections.list(super.getHeaderNames());
        for (String name : headerMap.keySet()) {
            names.add(name);
        }
        return Collections.enumeration(names);
    }

    @Override
    public Enumeration<String> getHeaders(String name) {
        List<String> values = Collections.list(super.getHeaders(name));
        if (headerMap.containsKey(name)) {
            values.add(headerMap.get(name));
        }
        return Collections.enumeration(values);
    }

    @Override

    public String getParameter(String name) {//重写getParameter,代表参数从当前类中的map获取

        String[]values = params.get(name);

        if(values == null || values.length == 0) {

            return null;

        }

        return values[0];

    }



    @Override
    public String[] getParameterValues(String name) {//同上

        return params.get(name);

    }
}

Filter中操作如下

@Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        SafeboxRequestWrapper safeboxRequestWrapper = new SafeboxRequestWrapper(request);
        //TODO 此处对头信息或者请求参数进行操作
        
        //把包装类替代request传递下去
          filterChain.doFilter(safeboxRequestWrapper,response);
       
    }

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐