首页 > 其他分享 >SpringBoot利用Filter获取请求数据request和修改返回response中的数据

SpringBoot利用Filter获取请求数据request和修改返回response中的数据

时间:2023-04-19 17:26:45浏览次数:40  
标签:throws request public Filter IOException Override import servlet response

WrapperedRequest

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

public class WrapperedRequest extends HttpServletRequestWrapper {

    private String requestBody = null;
    HttpServletRequest req = null;

    public WrapperedRequest(HttpServletRequest request) {
        super(request);
        this.req = request;
    }

    public WrapperedRequest(HttpServletRequest request, String requestBody) {
        super(request);
        this.requestBody = requestBody;
        this.req = request;
    }

    /**
     * (non-Javadoc)
     *
     * @see javax.servlet.ServletRequestWrapper#getReader()
     */
    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new StringReader(requestBody));
    }

    /**
     * (non-Javadoc)
     *
     * @see javax.servlet.ServletRequestWrapper#getInputStream()
     */
    @Override
    public ServletInputStream getInputStream() throws IOException {
        return new ServletInputStream() {
            private InputStream in = new ByteArrayInputStream(
                    requestBody.getBytes(req.getCharacterEncoding()));

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

            @Override
            public boolean isFinished() {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean isReady() {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
                // TODO Auto-generated method stub

            }
        };
    }
}

WrapperedResponse

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

public class WrapperedResponse extends HttpServletResponseWrapper {

    private ByteArrayOutputStream buffer = null;
    private ServletOutputStream out = null;
    private PrintWriter writer = null;

    public WrapperedResponse(HttpServletResponse resp) throws IOException {
        super(resp);
        // 真正存储数据的流
        buffer = new ByteArrayOutputStream();
        out = new WapperedOutputStream(buffer);
        writer = new PrintWriter(new OutputStreamWriter(buffer, this.getCharacterEncoding()));
    }

    /**
     * 重载父类获取outputstream的方法
     */
    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return out;
    }

    /**
     * 重载父类获取writer的方法
     */
    @Override
    public PrintWriter getWriter() throws UnsupportedEncodingException {
        return writer;
    }

    /**
     * 重载父类获取flushBuffer的方法
     */
    @Override
    public void flushBuffer() throws IOException {
        if (out != null) {
            out.flush();
        }
        if (writer != null) {
            writer.flush();
        }
    }

    @Override
    public void reset() {
        buffer.reset();
    }

    /**
     * 将out、writer中的数据强制输出到WapperedResponse的buffer里面,否则取不到数据
     */
    public byte[] getResponseData() throws IOException {
        flushBuffer();
        return buffer.toByteArray();
    }

    /**
     * 内部类,对ServletOutputStream进行包装
     */
    private class WapperedOutputStream extends ServletOutputStream {
        private ByteArrayOutputStream bos = null;

        public WapperedOutputStream(ByteArrayOutputStream stream) throws IOException {
            bos = stream;
        }

        @Override
        public void write(int b) throws IOException {
            bos.write(b);
        }

        @Override
        public void write(byte[] b) throws IOException {
            bos.write(b, 0, b.length);
        }

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {

        }
    }
}

数据处理

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

@Slf4j
public class DataFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        String contentType = request.getContentType();
        WrapperedResponse wrapResponse = new WrapperedResponse((HttpServletResponse) response);
        WrapperedRequest wrapRequest;
        // 表单请求数据自行处理解密
        if (contentType == null || !contentType.contains("multipart/form-data")) {
            String requestBody = getRequestBody((HttpServletRequest) request);
            log.info("请求数据:" + requestBody);
			// todo
            //处理请求报文
            String requestBodyStr =requestBody;
            wrapRequest = new WrapperedRequest((HttpServletRequest) request, requestBodyStr);
            chain.doFilter(wrapRequest, wrapResponse);
        } else {
            chain.doFilter(request, wrapResponse);
        }

        byte[] data = wrapResponse.getResponseData();
        String responseBody = new String(data, StandardCharsets.UTF_8);
        log.info("原始返回数据: " + responseBody);
        // 返回报文
        String responseBodyStr = responseBody;
        log.info("处理后返回数据: " + responseBodyStr);
        writeResponse(response, responseBodyStr);
    }

    @Override
    public void destroy() {

    }


    private String getRequestBody(HttpServletRequest req) {
        try {
            BufferedReader reader = req.getReader();
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (IOException e) {
            log.info("请求体读取失败" + e.getMessage());
        }
        return "";
    }

    private void writeResponse(ServletResponse response, String responseString) throws IOException {
        response.setContentLength(-1);
        PrintWriter out = response.getWriter();
        out.print(responseString);
        out.flush();
        out.close();
    }

}

标签:throws,request,public,Filter,IOException,Override,import,servlet,response
From: https://www.cnblogs.com/fchhk-blog/p/17333961.html

相关文章

  • 一篇博客上手request和response
    概念request:获取请求数据response:设置响应数据Requestrequest继承体系ServletRequest——Java提供的请求对象根接口HttpServletRequest——Java提供的对http协议封装的请求对象接口RequestFacade——tomcat实现定义类request获取数据packagecom.itheijma.web;importj......
  • filter-policy、route-policy和ip-prefix默认处理方式
    1、route-policy    默认情况下是拒绝所有路由的,如果没有按照特定条件对路由进行匹配和允许,那么所有的路由都将被拒绝。因此,在配置route-policy时,需要明确地指定允许的路由条目。   也可以在最后加个空node,[Huawei]route-policynamepermit node102、ip-prefix......
  • jmeter取样器javaRequest脚本8
    1,创建一个maven工程2,通过maven编译打包生成一个jar包3,重启jmeter,新建javarequest请求4,开始执行脚本本文永久更新地址:1,创建一个maven工程在pom.xml文件中添加maven下载地址:https://mvnrepository.com/artifact/org.apache.jmeter/ApacheJMeter_java/5.4.1<depe......
  • asp.net mvc 之旅 —— 第六站 ActionFilter的应用及源码分析
       这篇文章我们开始看一下ActionFilter,从名字上其实就大概知道ActionFilter就是Action上的Filter,对吧,那么Action上的Filter大概有几个呢???这个问题其实还是蛮简单的,因为我们听说Mvc本身就是一个扩展性极强的框架,自然就是层层有拦截,层层有过滤,对吧,比如我们看到的如下Control......
  • requests代理设置
    和urllib一样,多的介绍就不说了,直接上代码:importrequestsproxies={"http":"http://user:[email protected]:80","https":"http://10.10.1.10:1080",}requests.get("https://www.geekdigging.com/",proxies=proxies)......
  • 虚拟机ubuntu22.4报错ok_update_request:I/oerror, dev fdo, sector 0 op OX0:(READ)tl
    ok_update_request:I/oerror,devfdo,sector0opOX0:(READ)tlags0x0phys_segprioclass0BufferI/oerrorondevfdo,logicalblock0,asyncpageread如下图 不管你用的HYPER-V创建虚拟机,还是VMVBOX等。只要找到这里: 把DVD/CD或者软驱修改为物理驱动器,即可。 ......
  • requests如何不使用系统代理
    1.指定域名不使用代理importosimportrequestsos.environ['NO_PROXY']='stackoverflow.com'response=requests.get('http://www.stackoverflow.com')2.设置代理为Noneimportrequestsproxies={"http":None,"......
  • flask请求上下文分析(request原理)、wtforms
    上节回顾#1蓝图第一步:导入第二步:实例化得到对象,可以指定static和templates第三步:app中注册蓝图,注册蓝图时,可以指定前缀第四步:使用蓝图,注册路由,注册请求扩展#2g对象当次请求的全局对象,在当次请求中可以放值和取值跟session的区别是session可......
  • PayloadTooLargeError: request entity too large错误解决
    这个错误通常是由于你正在尝试上传大于服务器最大允许大小的文件或数据导致的。这通常可以通过在服务器端进行一些配置更改来解决。如果您使用的是Node.js,您可以使用body-parser中间件来增加请求体的限制。例如,以下代码将允许请求体的最大大小为10MB:varbodyParser=require('body......
  • How to use Linux shell command filter the IP address All In One
    HowtouseLinuxshellcommandfiltertheIPaddressAllInOne如何使用Linuxshell命令过滤IP地址questionHowtofilteroutthereallyusefulIPaddressfromlongstrings?如何从长字符串中过滤出真正有用的IP地址?$cat./dd-ip-notice-robot.sh$./dd......