getReader() has already been called for this request 异常

ServletRequest的getReader()和getInputStream()两个方法只能被调用一次,而且不能两个都调用。那么如果Filter中调用了一次,在Controller里面就不能再调用了

会抛出异常:getReader() has already been called for this request异常

如果需要使用HttpServletRequest请求中的数据(记录日志, 数据检查等), 不建议使用filter, 可以通过spring aop进行;

@Aspect
@Order(5)
@Component
public class ControllerLogAspect {

    private Logger logger = Logger.getLogger(getClass());

    @Pointcut("execution(public * com.jceb.system.provider.controller..*.*(..))")
    public void controllerLog() {
    }

    @Before("controllerLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {

        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 只记录post方法
        if("POST".equals(request.getMethod())){
            // 记录下请求内容
            logger.info("请求URL : " + request.getRequestURL());
            logger.info("请求IP : " + request.getRemoteAddr());
            logger.info("请求方法 : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

            // 获取参数, 只取自定义的参数, 自带的HttpServletRequest, HttpServletResponse不管
            if (joinPoint.getArgs().length > 0) {
                for (Object o : joinPoint.getArgs()) {
                    if (o instanceof HttpServletRequest || o instanceof HttpServletResponse) {
                        continue;
                    }
                    logger.info("请求参数 : " + JSON.toJSONString(o));
                }
            }
        }
    }

    @AfterReturning(returning = "ret", pointcut = "controllerLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求,返回内容
        logger.info("返回 : " + JSON.toJSONString(ret));
    }


}


你可能感兴趣的:(代码)