在Spring AOP Aspect中取得Request, Session

在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);

  }
}

參考:

  • How to inject HttpServletRequest into a Spring AOP request (custom scenario)?
  • Spring AOP and aspect thread safety for an autowired HTTPServletRequest bean
  • How to get web session on Spring AOP
  • SpringMVC之RequestContextHolder分析

你可能感兴趣的:(在Spring AOP Aspect中取得Request, Session)