由于公司老项目的各种原因不能用springAOP做日志收集,而是采用Filter做,其中需要从filter中的request中获取参数,如果是get方式请求,可以从request.getParameter("key")获取,但如果是post请求,则需要从request.getInputStream()做相关转化才能获取,但是request的流只能读取一次,第二次就没办法读取了,导致后端controller接收到的参数为null。

为了解决这个问题,我们需要做个httpServletRequestWrapper的封装。借鉴一下博文:

https://blog.csdn.net/w_t_y_y/article/details/103407841

然后在我自己的拦截器中做了一个处理:

@Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        SysUserBehavior sysUserBehavior = new SysUserBehavior();

        HttpServletRequest wrapperRequest = null;
        String method = request.getMethod().toUpperCase();
        String type = request.getContentType();

        if (HttpMethod.POST.name().equals(method) && type.contains("application/json")) {
            wrapperRequest = new BodyReaderHttpServletRequestWrapper(request);
        }
        Map<String, String> requestMap = new HashMap<>();
        if (wrapperRequest == null) {
            Map<String, String[]> originRequestMap = request.getParameterMap();
            for (String key : originRequestMap.keySet()) {
                String[] values = originRequestMap.get(key);
                requestMap.put(key, values[0]);
            }
        }else {
            String param = ((BodyReaderHttpServletRequestWrapper)wrapperRequest).getBody();
            ObjectMapper objectMapper = new ObjectMapper();
            requestMap = objectMapper.readValue(param, HashMap.class);
        }
        String roleCode = requestMap.get("role");
        String app = requestMap.get("app");

        sysUserBehavior.setApp(app);
        sysUserBehavior.setRoleCode(roleCode);

        if (wrapperRequest == null) {
            filterChain.doFilter(request,response);
        }else{
            filterChain.doFilter(wrapperRequest,response);
        }
        try{
            startLog(request,response,sysUserBehavior,startTime);
        }catch (Exception e){
            e.printStackTrace();
        }
        SpringMvcUtils.renderError(HttpStatus.FORBIDDEN.value(),"对不起,你没有该权限!");

    }

 

最后修改于 2021-07-16 09:23:41
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付
上一篇