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

  }
}

參考:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。