溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Filter中獲取傳遞參數(shù)的方式

發(fā)布時間:2021-08-30 09:33:21 來源:億速云 閱讀:119 作者:chen 欄目:開發(fā)技術(shù)

這篇文章主要講解了“Filter中獲取傳遞參數(shù)的方式”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“Filter中獲取傳遞參數(shù)的方式”吧!

目錄
  • Filter中獲取傳遞參數(shù)

    • 1. GET 傳遞

    • 2. Post 傳遞

      • XyRequestWrapper 類

      • XySecurityFilter

Filter中獲取傳遞參數(shù)

1. GET 傳遞

參數(shù)可以直接通過request.getParameter獲取。

2. Post 傳遞

產(chǎn)生不能過直接從request.getInputStream() 讀取,必須要進(jìn)行重新寫。(request.getInputStream()只能夠讀取一次)

方式:

通過重寫 HttpServletRequestWrapper 類 獲取getInputStream中的流數(shù)據(jù),然后在將body數(shù)據(jù)進(jìn)行重新寫入傳遞下去。

XyRequestWrapper 類
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);
    } 
 
    /**
     * 設(shè)置自定義post參數(shù) //
     *
     * @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
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;
 
    //驗(yàn)證 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("進(jìn)入XySecurityFilter!");
        // 參數(shù)集合 初始化
        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);
        /**
         * 驗(yàn)證通用請求頭是否完整
         */
        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;
        }
 
        // 防止流讀取一次后就沒有了, 所以需要將流繼續(xù)寫出去
        XyRequestWrapper requestWrapper = new XyRequestWrapper(req);
 
        /**
         * 校驗(yàn)token
         */
        /*********************************************************/ 
 
        /**
         * 獲取請求參數(shù)
         */
        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());
        } 
 
        /**
         * 驗(yàn)證簽名是否合法
         */
        /***************************************/
 
        //設(shè)置企業(yè)信息(自定義參數(shù))
        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() { 
    }
}

感謝各位的閱讀,以上就是“Filter中獲取傳遞參數(shù)的方式”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對Filter中獲取傳遞參數(shù)的方式這一問題有了更深刻的體會,具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識點(diǎn)的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI