美文网首页
在Spring AOP Aspect中取得Request, Se

在Spring AOP Aspect中取得Request, Se

作者: 黎明神话 | 来源:发表于2019-07-19 15:05 被阅读0次

在Spring AOP Aspect中取得Request及Session的方法如下。

在Spring AOP 中直接注入HttpServletRequest

@Aspect
public class MyControllerAspect {

  @Autowired
  private HttpServletRequest request; // 直接注入

  @Before("execution(* idv.matthung.controller.MyController.*(..))")
  public void before(JoinPoint joinPoint) {

    String userName = (String) request.getAttribute("userName");
    System.out.println(userName);

  }
}

在Spring AOP 中透過[RequestContextHolder.currentRequestAttributes()](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/context/request/RequestContextHolder.html#currentRequestAttributes--)取得Request。

@Aspect
public class MyControllerAspect {

  @Before("execution(* idv.matthung.controller.MyController.*(..))")
  public void before(JoinPoint joinPoint) {

    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

    String userName = (String) request.getAttribute("userName");
    System.out.println(userName);

  }
}

在Spring AOP 中直接注入HttpSession

@Aspect
public class MyControllerAspect {

  @Autowired
  private HttpSession session; // 直接注入

  @Before("execution(* idv.matthung.controller.MyController.*(..))")
  public void before(JoinPoint joinPoint) {

    String userName = (String) session.getAttribute("userName");
    System.out.println(userName);

  }
}

在Spring AOP 中透過[RequestContextHolder.currentRequestAttributes()](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/context/request/RequestContextHolder.html#currentRequestAttributes--)取得Session。

@Aspect
public class MyControllerAspect {

  @Before("execution(* idv.matthung.controller.MyController.*(..))")
  public void before(JoinPoint joinPoint) {

    HttpSession session = (HttpSession) RequestContextHolder.currentRequestAttributes().resolveReference(RequestAttributes.REFERENCE_SESSION);

    String userName = (String) session.getAttribute("userName");
    System.out.println(userName);

  }
}

參考:

相关文章

网友评论

      本文标题:在Spring AOP Aspect中取得Request, Se

      本文链接:https://www.haomeiwen.com/subject/kzfslctx.html