首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring AOP & HttpServletRequest

Spring AOP & HttpServletRequest
EN

Stack Overflow用户
提问于 2020-05-28 04:49:14
回答 2查看 435关注 0票数 0

我正在处理一个注释,该注释将向其他微服务发送一些审核事件。比方说,我正在创建一个实体,并且我的Rest控制器上有一个方法add

代码语言:javascript
复制
@PostMapping
@Audit
public ResponseEntity<EntityDTO> add(EntityDTO entity){
...
}

我定义了一个与@Audit注释相关联的适当方面。

但是这里有一个技巧,审计事件的性质决定了我需要从HttpServletRequest本身提取一些元数据。

而且我不想通过添加(或替换我唯一的参数) HttpServletRequest对象来修改我的签名。

我如何将HttpServletRequest传递到我的方面中?有什么高雅的方法吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-05-28 05:06:30

由于您使用的是spring MVC,请考虑使用Spring MVC拦截器而不是“通用”方面。它们由Spring MVC原生支持,并且可以提供对处理程序和HttpServletRequest对象的访问

有关使用拦截器和常规配置的信息,请参见this tutorial

有关处理程序的一些信息,请参见This thread

代码语言:javascript
复制
final HandlerMethod handlerMethod = (HandlerMethod) handler; // this is what you'll get in the methods of the interceptor in the form of Object
final Method method = handlerMethod.getMethod();
票数 1
EN

Stack Overflow用户

发布于 2020-05-28 10:17:40

下面是如何使用Spring AOP来完成此操作。

示例注释。

代码语言:javascript
复制
@Retention(RUNTIME)
@Target({ TYPE, METHOD })
public @interface Audit {
    String detail();
}

以及相应的方面

代码语言:javascript
复制
@Component
@Aspect
public class AuditAspect {

    @Around("@annotation(audit) && within(com.package.web.controller..*)")
    public Object audit(ProceedingJoinPoint pjp, Audit audit) throws Throwable {
        // Get the annotation detail
        String detail = audit.detail();
        Object obj = null;
        //Get the HttpServletRequest currently bound to the thread.
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        try {
            // audit code
            System.out.println(detail);
            System.out.println(request.getContextPath());
            obj = pjp.proceed();
        } catch (Exception e) {
            // Log Exception;
        }
        // audit code
        return obj;
    }
}

注: Op已接受基于拦截器的答案。这个答案就是演示Spring AOP代码来实现这个要求。

希望这能有所帮助

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62052618

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档