Spring切面中,如何获取Request对象

本文讲述了在系统中使用Spring切面进行用户操作日志记录时,遇到的HttpServletRequest空指针异常问题。解决方案是在web.xml中添加RequestContextListener以确保ServletRequestAttributes不为空。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景

最近,给系统添加用户的操作日志,用到了切面,需要获取相关参数,对于大部分码农来说,

还是习惯了使用HttpServletRequest对象

获取方式

    @AfterReturning("logPoinCut()")
    public void saveSysLog(JoinPoint joinPoint){
        //获取request对象
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //.....其他操作
    }

碰到的问题

1 在测试过程中,发现报空指针异常, ServletRequestAttributes对象为null

解决办法

1 在工程的web.xml中配置如下监听器

    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值