服务器之家

服务器之家 > 正文

Filter中获取传递参数方式(解决post请求参数问题)

时间:2021-12-08 11:55     来源/作者:PowerMan_Frank

Filter中获取传递参数

1. GET 传递

参数可以直接通过request.getParameter获取。

2. Post 传递

产生不能过直接从request.getInputStream() 读取,必须要进行重新写。(request.getInputStream()只能够读取一次)

方式:

通过重写 HttpServletRequestWrapper 类 获取getInputStream中的流数据,然后在将body数据进行重新写入传递下去。

XyRequestWrapper 类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package com.xy.boot.cmiap.filter;
import com.alibaba.fastjson.JSONObject;
import com.xy.boot.common.util.StringUtils;
import org.apache.catalina.servlet4preview.http.HttpServletRequestWrapper;
import org.apache.commons.codec.Charsets;
 
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
 
/**
 * Created by fuwenshen
 * Date:2018/10/26
 * Time:12:21
 */
public class XyRequestWrapper extends HttpServletRequestWrapper {
    private String body;
    public XyRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            InputStream inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                stringBuilder.append("");
            }
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    throw ex;
                }
            }
        }
        body = stringBuilder.toString();
    }
 
    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes("UTF-8"));
        ServletInputStream servletInputStream = new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }
 
            @Override
            public boolean isReady() {
                return false;
            }
 
            @Override
            public void setReadListener(ReadListener readListener) {
 
            }
 
            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
        return servletInputStream;
    }
 
    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream(), Charsets.UTF_8));
    }
 
    public String getBody() {
        return this.body;
    }
 
    @Override
    public String getParameter(String name) {
        return super.getParameter(name);
    }
 
    @Override
    public Map<String, String[]> getParameterMap() {
        return super.getParameterMap();
    }
 
    @Override
    public Enumeration<String> getParameterNames() {
        return super.getParameterNames();
    }
 
    @Override
    public String[] getParameterValues(String name) {
        return super.getParameterValues(name);
    }
 
    /**
     * 设置自定义post参数 //
     *
     * @param paramMaps
     * @return
     */
    public void setParamsMaps(Map paramMaps) {
        Map paramBodyMap = new HashMap();
        if (!StringUtils.isEmpty(body)) {
            paramBodyMap = JSONObject.parseObject(body, Map.class);
        }
        paramBodyMap.putAll(paramMaps);
        body = JSONObject.toJSONString(paramBodyMap);
    }
}

XySecurityFilter

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package com.xy.boot.cmiap.filter;
import com.alibaba.fastjson.JSONObject;
import com.xy.boot.cmiap.bo.VerifyTokenResultBO;
import com.xy.boot.cmiap.constant.HttpConstant;
import com.xy.boot.cmiap.entity.enums.XyHttpCodeEnum;
import com.xy.boot.cmiap.service.IXySecurityService;
import com.xy.boot.cmiap.service.helper.XyHttpSecurityHelper;
import com.xy.boot.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
 
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
 
/**
 * Created by fuwenshen
 * Date:2018/10/29
 * Time:15:36
 */
@Component
@Slf4j
@WebFilter(filterName = "xySecurityFilter", urlPatterns = {"/api/adv/*"})
public class XySecurityFilter implements Filter {
 
    @Value("${verify_token_switch}")
    private boolean tokenSwitch;
    @Value("${zy.app_secret}")
    private String zyAppSecret;
    @Value("${zy.token}")
    private String zyToken;
 
    //验证 token bo
    private VerifyTokenResultBO tokenBO=null;
 
    @Autowired
    private IXySecurityService iXySecurityService;
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
 
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.debug("进入XySecurityFilter!");
        // 参数集合 初始化
        TreeMap paramsMaps = new TreeMap();
        String token = null, v = null, timestamp = null, sign = null;
 
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        /**
         * 验证通用请求头是否完整
         */
        token = req.getHeader(HttpConstant.TOKEN);
        v = req.getHeader(HttpConstant.V);
        timestamp = req.getHeader(HttpConstant.TIMESTAMP);
        sign = req.getHeader(HttpConstant.SIGN);
        if (StringUtils.isEmpty(token) || StringUtils.isEmpty(v) || StringUtils.isEmpty(timestamp) || StringUtils.isEmpty(sign)) {
            resp.sendError(XyHttpCodeEnum.ILLEGAL_REQUEST.getCode(), XyHttpCodeEnum.ILLEGAL_REQUEST.getMessage());
            return;
        }
 
        // 防止流读取一次后就没有了, 所以需要将流继续写出去
        XyRequestWrapper requestWrapper = new XyRequestWrapper(req);
 
        /**
         * 校验token
         */
        /*********************************************************/
 
        /**
         * 获取请求参数
         */
        if ("POST".equals(req.getMethod().toUpperCase())) {
            String body = requestWrapper.getBody();
            paramsMaps = JSONObject.parseObject(body, TreeMap.class);
            log.debug("parameterMap:" + paramsMaps.toString());
 
        } else {
 
            Map<String, String[]> parameterMap = requestWrapper.getParameterMap();
            Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
            Iterator<Map.Entry<String, String[]>> iterator = entries.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String[]> next = iterator.next();
                paramsMaps.put(next.getKey(), next.getValue()[0]);
            }
            log.debug("parameterMap:" + paramsMaps.toString());
        }
 
        /**
         * 验证签名是否合法
         */
        /***************************************/
 
        //设置企业信息(自定义参数)
        if(tokenBO!=null){
            Map paramsPlus = new HashMap();
            paramsPlus.put(HttpConstant.TOKEN, tokenBO.getTokenCode());
            paramsPlus.put(HttpConstant.APPID, tokenBO.getAppid());
            requestWrapper.setParamsMaps(paramsPlus);
        }
 
        chain.doFilter(requestWrapper, response);
    }
 
    @Override
    public void destroy() {
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/fuwenshen/article/details/90203395

相关文章

热门资讯

yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部