AdSense

網頁

2018/2/12

在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()取得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()取得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);
    
  }
}

如果覺得文章有幫助的話還幫忙點個Google廣告,感恩。


參考:

沒有留言:

AdSense