bingoshe
V2EX  ›  Java

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

  •  
  •   bingoshe · Jul 8, 2022 · 2141 views
    This topic created in 1587 days ago, the information mentioned may be changed or developed.
    添加了 xss 过滤后,因为读取了一次 body ,再次读取时无法读取,按照网上教程重写了 ServletInputStream ,可以手动重复读 body ,但是 controller 的 post 参数无法自动注入
    Supplement 1  ·  Jul 8, 2022
    qinxi
    qinxi
    Jul 8, 2022
    1
    参考 CommonsRequestLoggingFilter
    核心由 AbstractRequestLoggingFilter 提供
    LeegoYih
    LeegoYih
    Jul 8, 2022
    2
    用拦截器吧


    新建一个类,实现`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
    wolfie
    Jul 8, 2022
    3
    贴代码
    tmdbbr
    tmdbbr
    Jul 8, 2022
    4
    有意思 我看看我们咋个解决得
    chendy
    chendy
    Jul 8, 2022
    6
    歪个楼,新系统新前端框架下,xss 过滤还有必要么?……
    bingoshe
    bingoshe
    OP
    Jul 8, 2022
    7
    @wolfie 代码贴上了
    项目比较老不是 springboot 的
    wolfie
    wolfie
    Jul 8, 2022
    8
    流的可重复读取,提现在哪里。
    javax.servlet.ServletRequestWrapper#getInputStream
    bingoshe
    bingoshe
    OP
    Jul 8, 2022
    9
    @wolfie 返回了自定义的 ServletInputStream 实现类
    wolfie
    wolfie
    Jul 8, 2022
    10
    每次调用 XssHttpServletRequest#getInputStream ,都会调用 super#getInputStream 啊
    goalidea
    goalidea
    Jul 10, 2022❤️1
    11
    应该出在 `XssHttpServletRequest.getInputStream()` 中的 `final ByteArrayInputStream bais = new ByteArrayInputStream(inputHandlers(super.getInputStream()).getBytes());` 这行代码。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   3862 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 05:43 · PVG 13:43 · LAX 21:43 · JFK 00:43
    ♥ Do have faith in what you're doing.