Springboot如何使用filter对request body参数进行校验
作者:Jordan 发布时间:2023-09-14 05:28:46
标签:Springboot,filter,request,body,校验
使用filter对request body参数进行校验
@Slf4j
public class ParameterCheckServletRequestWrapper extends HttpServletRequestWrapper {
private byte[] requestBody;
private Charset charSet;
public ParameterCheckServletRequestWrapper(HttpServletRequest request) {
super(request);
//缓存请求body
try {
String requestBodyStr = getRequestPostStr(request);
if (StringUtils.isNotBlank(requestBodyStr)) {
JSONObject resultJson = JSONObject.fromObject(requestBodyStr.replace("\"", "'"));
Object[] obj = resultJson.keySet().toArray();
for (Object o : obj) {
resultJson.put(o, StringUtils.trimToNull(resultJson.get(o).toString()));
}
requestBody = resultJson.toString().getBytes(charSet);
} else {
requestBody = new byte[0];
}
} catch (IOException e) {
log.error("", e);
}
}
public String getRequestPostStr(HttpServletRequest request)
throws IOException {
String charSetStr = request.getCharacterEncoding();
if (charSetStr == null) {
charSetStr = "UTF-8";
}
charSet = Charset.forName(charSetStr);
return StreamUtils.copyToString(request.getInputStream(), charSet);
}
/**
* 重写 getInputStream()
*/
@Override
public ServletInputStream getInputStream() {
if (requestBody == null) {
requestBody = new byte[0];
}
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(requestBody);
return new ServletInputStream() {
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
@Override
public int read() {
return byteArrayInputStream.read();
}
};
}
/**
* 重写 getReader()
*/
@Override
public BufferedReader getReader() {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
}
public class ParameterCheckFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
ParameterCheckServletRequestWrapper myWrapper = new ParameterCheckServletRequestWrapper((HttpServletRequest) servletRequest);
filterChain.doFilter(myWrapper, servletResponse);
}
@Override
public void destroy() {
}
}
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean authFilterRegistrationBean() {
FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setName("parameterCheckFilter");
registrationBean.setFilter(new ParameterCheckFilter());
registrationBean.setOrder(1);
registrationBean.addUrlPatterns("/*");
return registrationBean;
}
}
通过filter修改body参数的思路
知识点
1、HttpServletRequestWrapper
2、filter
步骤
1、新建MyHttpServletRequestWrapper继承HttpServletRequestWrapper
2、讲传入的body赋值给自己的body(如下)
package com.orisdom.modules.common.filter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.orisdom.modules.monitor.dto.input.MonitorPointQueryPara;
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;
import java.nio.charset.Charset;
/**
* @author xiaokang
* @description
* @date 2021/6/11 10:56
*/
public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {
private String tempBody;
public MyHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
this.tempBody = getBody(request);
System.out.println(tempBody);
}
/**
* 获取请求体
* @param request 请求
* @return 请求体
*/
private String getBody(HttpServletRequest request) {
try {
ServletInputStream stream = request.getInputStream();
String read = "";
StringBuilder stringBuilder = new StringBuilder();
byte[] b = new byte[1024];
int lens = -1;
while ((lens = stream.read(b)) > 0) {
stringBuilder.append(new String(b, 0, lens));
}
return stringBuilder.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 获取请求体
* @return 请求体
*/
public String getBody() {
MonitorPointQueryPara para = JSON.parseObject(tempBody, MonitorPointQueryPara.class);
para.setName("1232321321");
tempBody = JSONObject.toJSONString(para);
return tempBody;
}
/**
* 需要重写这个方法
* @return
* @throws IOException
*/
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
/**
* 需要重写这个方法
* @return
* @throws IOException
*/
@Override
public ServletInputStream getInputStream() throws IOException {
// 创建字节数组输入流
final ByteArrayInputStream bais = new ByteArrayInputStream(tempBody.getBytes(Charset.defaultCharset()));
return 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 bais.read();
}
};
}
}
1.新建MyFilter 继承 Filter
2.添加@WebFilter注解
3.启动类添加@ServletComponentScan(如下)
package com.orisdom.modules.common.filter;
import org.springframework.core.annotation.Order;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* @author xiaokang
* @description
* @date 2021/6/11 9:47
*/
@WebFilter
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
MyHttpServletRequestWrapper myHttpServletRequestWrapper = new MyHttpServletRequestWrapper((HttpServletRequest) servletRequest);
// 相当于赋值
myHttpServletRequestWrapper.getBody();
// 自己定义的MyHttpServletRequestWrapper
filterChain.doFilter(myHttpServletRequestWrapper, servletResponse);
System.out.println(11111111);
}
@Override
public void destroy() {
}
}
没加之前
加了之后
来源:https://blog.csdn.net/u012661496/article/details/83653206
0
投稿
猜你喜欢
- 1.依赖maven依赖如下,需要说明的是,spring-boot-starter-data-redis里默认是使用lettuce作为redi
- 目录问题为每个request设置超时值Http Handler给Request加上超时处理抛出正确的异常使用Handler总结HttpCli
- 三种得到LinearInflater的方法a. LayoutInflater inflater = getLayoutInflater();
- 这篇文章主要介绍了mybatis使用pagehelper插件过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习
- Android静默安装的方法,静默安装就是绕过安装程序时的提示窗口,直接在后台安装。注意:静默安装的前提是设备有ROOT权限。代码如下:/*
- 本文较为详细的总结分析了Android编程下拉菜单spinner用法。分享给大家供大家参考,具体如下:Spinner控件也是一种列表类型的控
- 概念引入我们都知道,Java 创建的对象都是被分配到堆内存上,但是事实并不是这么绝对,通过对Java对象分配的过程分析,可以知道有两个地方会
- 前面,学了物体的移动功能,现在来学一下C#实现鼠标控制摄像机(视角)移动。代码如下:C#脚本(在Unity 5.5.1 下能运行):usin
- 原来一直使用shiro做安全框架,配置起来相当方便,正好有机会接触下SpringSecurity,学习下这个。顺道结合下jwt,把安全信息管
- Spring Boot 异常处理异常处理是一种识别并响应错误的一致性机制,异常机制可以把程序中的异常处理代码和正常的业务逻辑代码分离,包装程
- 直接上代码public static class ImageCompress { /// <su
- 概述从今天开始, 小白我将带大家开启 Java 数据结构 & 算法的新篇章.贪心算法贪心算法 (Greedy Algorithm)
- 在做2048这个游戏时,因为菜单页面还能查看游戏规则,而这些规则又不在同一个页上,所以需要滑动页面实现页面切换,但是仅仅使用unity提供的
- #include<iostream>#include<assert.h>using namespace std;st
- 本文实例为大家分享了Android高德地图marker自定义弹框窗口的具体代码,供大家参考,具体内容如下最终效果:1.gradle里添加高德
- 使用 replace 函数动态填充字符串String str="Hello {0},我是 {1},今年{2}岁"
- 在实际的工作中直接使用反射的机会比较少,有印象的就是一次自己做的WinForms小工具的时候利用反射来动态获取窗体上的每个控件,并且为必要的
- using System; using System.Drawing; using System.Windows.Forms; using
- 本文实例为大家分享了Android ViewPager指示器的制作方法,供大家参考,具体内容如下1.概述ViewPageIndicator这
- 一、抽象类1.抽象类1.1抽象类的定义在Java面向对象当中,所有的对象都是用过类进行描绘的,但是并不是所有的类都是用来描绘对象的,如果一个