bingoshe
V2EX  ›  Java

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

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


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