首页 > 其他分享 >SpringBoot拦截器中读取POST请求体参数

SpringBoot拦截器中读取POST请求体参数

时间:2024-09-19 11:01:48浏览次数:1  
标签:拦截器 return SpringBoot request CustomHttpServletRequestWrapper import POST servle

CustomHttpServletRequestWrapper.java:包装请求,缓存请求体数据,重写读取数据方法

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class CustomHttpServletRequestWrapper extends HttpServletRequestWrapper {

    /**
     * 缓存请求体数据
     */
    private byte[] requestBody;

    public CustomHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        // 读取请求体并缓存
        requestBody = request.getInputStream().readAllBytes();
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        // 返回缓存的请求体字节流
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(requestBody);
        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }

            @Override
            public boolean isFinished() {
                return byteArrayInputStream.available() == 0;
            }

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

            @Override
            public void setReadListener(ReadListener readListener) {
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    public byte[] getRequestBody() {
        return this.requestBody;
    }
}

RequestBodyCachingFilter:包装POST请求

import cn.hutool.extra.servlet.ServletUtil;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
// 确保过滤器优先执行
@Order(1)  
public class RequestBodyCachingFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        if (ServletUtil.METHOD_POST.equalsIgnoreCase(httpServletRequest.getMethod())) {
            // 包装 HttpServletRequest
            CustomHttpServletRequestWrapper wrappedRequest = new CustomHttpServletRequestWrapper(httpServletRequest);
            // 继续过滤链,传递包装后的请求对象
            chain.doFilter(wrappedRequest, response);
        } else {
            chain.doFilter(request, response);
        }
    }
}

CustomInterceptor.java:拦截器中取POST请求体的数据

import cn.hutool.extra.servlet.ServletUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

public class CustomInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (ServletUtil.METHOD_POST.equalsIgnoreCase(request.getMethod()) && request instanceof CustomHttpServletRequestWrapper) {
            CustomHttpServletRequestWrapper wrappedRequest = (CustomHttpServletRequestWrapper) request;
            String requestBody = getRequestBody(wrappedRequest);
            System.out.println("请求体内容为 >>> " + requestBody);
        }
        return true;
    }

    private String getRequestBody(CustomHttpServletRequestWrapper request) throws UnsupportedEncodingException {
        byte[] buf = request.getRequestBody();
        if (buf.length > 0) {
            return new String(buf, 0, buf.length, request.getCharacterEncoding());
        }
        return null;
    }
}

WebConfig:配置拦截器生效

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CustomInterceptor());
    }
}

标签:拦截器,return,SpringBoot,request,CustomHttpServletRequestWrapper,import,POST,servle
From: https://www.cnblogs.com/hhddd-1024/p/18420180

相关文章

  • 基于SpringBoot + Uniapp的公开课管理小程序(角色:学生、教师、管理员)
    文章目录前言一、详细操作演示视频二、具体实现截图三、技术栈1.前端-Vue.js2.后端-SpringBoot3.数据库-MySQL4.系统架构-B/S四、系统测试1.系统测试概述2.系统功能测试3.系统测试结论五、项目代码参考六、数据库代码参考七、项目论文示例八、一站式毕设支持服务结语......
  • 基于SpringBoot + Vue的大学生平时成绩量化管理系统(角色:学生、教师、管理员)
    文章目录前言一、详细操作演示视频二、具体实现截图三、技术栈1.前端-Vue.js2.后端-SpringBoot3.数据库-MySQL4.系统架构-B/S四、系统测试1.系统测试概述2.系统功能测试3.系统测试结论五、项目代码参考六、数据库代码参考七、项目论文示例八、一站式毕设支持服务结语......
  • 基于springboot乘用车汽车市场销量情况分析可视化系统
    前言......
  • 基于springboot城市路边停车系统小程序
    前言......
  • 基于SpringBoot+Vue的影视剧评论系统 ---附源码 78088
    目  录摘要Abstract1绪论1.1研究背景与意义1.2国内外研究现状1.3论文结构与章节安排2 影视剧评论系统分析2.1可行性分析2.1.1技术可行性分析2.1.2经济可行性分析2.1.3法律可行性分析2.2系统功能分析2.2.1功能性分析2.3系统用例分析......
  • springboot乡村旅游管理---附73081
    摘 要随着乡村旅游的蓬勃发展,传统的管理方式已难以满足日益增长的游客需求和市场变化。因此,借助现代信息技术手段,构建基于SpringBoot的乡村乡村旅游管理显得尤为重要。该系统旨在通过整合乡村旅游资源,提供智能化的管理服务,促进乡村旅游产业的健康发展,为游客提供更加优质......
  • 基于SpringBoot的网上招聘系统的设计与实现---附源码72387
    目 录第1章引 言1.1选题背景1.2研究现状1.3论文结构安排第2章系统的需求分析2.1系统可行性分析2.1.1技术方面可行性分析2.1.2经济方面可行性分析2.1.3法律方面可行性分析2.1.4操作方面可行性分析2.2系统功能需求分析2.3系统性......
  • springboot中如何使用线程池
    springboot中如何使用线程池在SpringBoot中使用线程池,你可以定义一个ThreadPoolTaskExecutor的Bean,然后在需要的地方使用@Autowired注入这个Bean。以下是一个配置线程池的例子:importorg.springframework.context.annotation.Bean;importorg.springframew......
  • SpringBoot+Vue餐馆点菜系统小程序
    SpringBoot+Vue餐馆点菜系统小程序项目描述餐馆点菜系统小程序是一个集成了多种功能的移动应用,旨在提供用户便捷的点餐体验和餐厅高效的订单管理。以下是针对您所提到的功能的简单介绍: 前台小程序:用户通过手机上的小程序,可以浏览餐厅的菜单、选择菜品、下单并完成支付。......
  • Springboot多种请求参数
        Springboot中有多种请求参数:简单参数、实体对象参数、数组、集合参数、日期时间参数、json参数……下列代码为每一种参数都写了一个简单的例子packagecom.wzb;importcom.wzb.pojo.Student;importcom.wzb.pojo.User;importorg.springframework.format.anno......