在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);
}
}
參考: