自定义HttpReqeust,解决request请求参数只能拿一次就失效的问题

定义一个过滤器并实现如下方法

@Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        super.doFilterInternal(new HttpRequestWrapper(request), response, filterChain);
    }

 

自定义HttpReqeust  HttpRequestWrapper
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.io.IOUtils;

/**
 * Wrap the generic httpServletRequest
 */
public class HttpRequestWrapper extends HttpServletRequestWrapper {
    
    private String body;
    
    private ServletInputStream inputStream;
    
    private BufferedReader reader;
    
    private String requestURI;
    
    private StringBuilder requestURL;
    
    private String servletPath;
    
    private Map<String, ?> params;
    
    public HttpRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        if (!isMultipart()) {
            preLoadBody(request);
        }
    }

    private void preLoadBody(HttpServletRequest request) throws IOException {
        Charset charset = Charset.forName(getCharacterEncoding());
        byte[] bodyBytes = IOUtils.toByteArray(request.getInputStream());
        body = new String(bodyBytes, charset);
        inputStream = new RequestCachingInputStream(body.getBytes(getCharacterEncoding()));
    }
    
    public final boolean isMultipart() {
        String contentType = getContentType();
        return contentType != null && contentType.toLowerCase().startsWith("multipart/");
    }
    
    @Override
    public final String getContentType() {
        String _contentType = getParameter("_contentType");
        if (_contentType != null) return _contentType;
        return super.getContentType();
    }

    public String getBody() {
        if (isMultipart()) throw new IllegalStateException("multipart request does not support preloaded body");
        return body;
    }

    @Override
    public String getMethod() {
        String _method = getParameter("_method");
        if (_method != null) return _method;
        return super.getMethod();
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (inputStream != null) return inputStream;
        return super.getInputStream();
    }

    @Override
    public BufferedReader getReader() throws IOException {
        if (reader == null) {
            reader = new BufferedReader(new InputStreamReader(inputStream, getCharacterEncoding()));
        }
        return reader;
    }
    
    @Override
    public final String getCharacterEncoding() {
        String defaultEncoding = super.getCharacterEncoding();
        return defaultEncoding != null ? defaultEncoding : "UTF-8";
    }
    
    public void setParams(Map<String, ?> params) {
        this.params = params;
    }
    /**
     * used to cache the request inputstream
     * @author sylorl
     * @date Mar 10, 2015
     */
    private static class RequestCachingInputStream extends ServletInputStream {
        
        private final ByteArrayInputStream inputStream;

        public RequestCachingInputStream(byte[] bytes) {
            inputStream = new ByteArrayInputStream(bytes);
        }

        @Override
        public int read() throws IOException {
            return inputStream.read();
        }
    }

    @Override
    public String getRequestURI() {
        if(this.requestURI == null) {
            return super.getRequestURI();
        }
        return super.getRequestURI();
    }

    @Override
    public StringBuffer getRequestURL() {
        if(this.requestURL == null) {
            return super.getRequestURL();
        }
        return new StringBuffer(this.requestURL.toString());
    }

    @Override
    public String getServletPath() {
        if(servletPath == null) {
            return super.getServletPath();
        }
        return this.servletPath;
    }

    public void setRequestURI(String requestURI, HttpServletRequest request) {
        this.servletPath = requestURI;
        this.requestURI = request.getContextPath() + requestURI;
        this.requestURL = new StringBuilder().append(request.getProtocol())
                                            .append("://")
                                            .append(request.getLocalAddr())
                                            .append("/")
                                            .append(servletPath);
    }
    
    
    public String[] getParameterValues(String name) {
        if(params != null) {
            Object v = params.get(name);
            if (v==null) {
                return null;
            } else if(v instanceof String[]) {
                return (String[]) v;
            } else if(v instanceof String) {
                return new String[]{(String) v};
            } else {
                return new String[]{v.toString()};
            }
        }
        return super.getParameterValues(name);
    }
    
    public String getParameter(String name) {
        if(params != null) {
            Object v = params.get(name);
            if(v == null) {
                return null;
            } else if(v instanceof String[]) {
                String []strArr = (String[]) v;
                if(strArr.length > 0){
                    return strArr[0];
                } else {
                    return null;
                }
            } else if(v instanceof String) {
                return (String) v;
            } else {
                return v.toString();
            }
        } 
        return super.getParameter(name);
    }
    
    @SuppressWarnings("unchecked")
    public Map<String, String[]> getParameterMap() {
        if(params != null){
            Map<String, String[]> map = new HashMap<String, String[]>();
            for(Object key:params.keySet()){
                 Object v = params.get((String)key);
                 String[] strArr = null;
                 if(v == null){
                     return null;
                 } else if(v instanceof String[]) {
                     strArr = (String[]) v;
                 } else if(v instanceof String) {
                     strArr = new String[1];
                     strArr[0] = (String) v;
                 } else {
                     strArr = new String[1];
                     strArr[0] = v.toString();
                 }
                 map.put((String)key, strArr);
            }
            return map;
        }
        return super.getParameterMap();
    }
}

 

 

转载于:https://www.cnblogs.com/binz/p/6924041.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值