请教下大佬们, spring mvc 添加过滤器后 post 参数无法自动注入问题

2022-07-08 10:14:24 +08:00
 bingoshe
添加了 xss 过滤后,因为读取了一次 body ,再次读取时无法读取,按照网上教程重写了 ServletInputStream ,可以手动重复读 body ,但是 controller 的 post 参数无法自动注入
1082 次点击
所在节点    Java
11 条回复
qinxi
2022-07-08 10:41:53 +08:00
参考 CommonsRequestLoggingFilter
核心由 AbstractRequestLoggingFilter 提供
LeegoYih
2022-07-08 10:46:18 +08:00
用拦截器吧


新建一个类,实现`HandlerInterceptor`接口:

```java
public class FooHandlerInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// TODO
return true;
}

public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// TODO
}

public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// TODO
}
}
```

新建一个配置类,实现`WebMvcConfigurer`接口,重写`addInterceptors`方法,将拦截器注册到 Spring MVC 容器中:

```
@Configuration
public class FooConfiguration implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new FooHandlerInterceptor()).addPathPatterns("/**");
}
}
```
wolfie
2022-07-08 10:47:37 +08:00
贴代码
tmdbbr
2022-07-08 10:56:25 +08:00
有意思 我看看我们咋个解决得
fiveStarLaoliang
2022-07-08 10:56:50 +08:00
chendy
2022-07-08 11:06:15 +08:00
歪个楼,新系统新前端框架下,xss 过滤还有必要么?……
bingoshe
2022-07-08 11:18:56 +08:00
@wolfie 代码贴上了
项目比较老不是 springboot 的
wolfie
2022-07-08 13:53:06 +08:00
流的可重复读取,提现在哪里。
javax.servlet.ServletRequestWrapper#getInputStream
bingoshe
2022-07-08 14:06:05 +08:00
@wolfie 返回了自定义的 ServletInputStream 实现类
wolfie
2022-07-08 14:11:39 +08:00
每次调用 XssHttpServletRequest#getInputStream ,都会调用 super#getInputStream 啊
goalidea
2022-07-10 09:42:19 +08:00
应该出在 `XssHttpServletRequest.getInputStream()` 中的 `final ByteArrayInputStream bais = new ByteArrayInputStream(inputHandlers(super.getInputStream()).getBytes());` 这行代码。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/864848

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX