Skip to main content
 首页 » 编程设计

java之在 SpringBoot 应用程序的 ControllerAdvice 中访问 HttpSession

2023年09月08日17zhwl

我想在 SpringBoot 应用程序的 session 中设置一些默认值。理想情况下,我正在考虑使用一个用 @ControllerAdvice 注释的类来设置默认值。这很有用,尤其是因为必须对所有页面执行代码片段。

有没有办法在用 @ControllerAdvice 注释的类中访问 HttpSession

请您参考如下方法:

您可以从您的@ControllerAdvice 中获取 session ,使用:

选项 1:

 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); 
 
HttpSession session = requeset.getSession(true);//true will create if necessary 

选项 2:

@Autowired(required=true) 
private HttpServletRequest request; 

选项 3:

@Context 
private HttpServletRequest request; 

下面是一个示例,说明我如何设计一个拦截所有 Controller 端点方法的 Controller 方面:

@Component 
@Aspect 
class ControllerAdvice{ 
 
     @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)") 
     void hasRequestMappingAnnotation() {} 
 
     @Pointcut("execution(* your.base.package..*Controller.*(..))") 
     void isMethodExecution() {} 
 
   /** 
    * Advice to be executed if this is a method being executed in a Controller class  within our package structure 
    * that has the @RequestMapping annotation. 
    * @param joinPoint 
    * @throws Throwable 
    */ 
    @Before("hasRequestMappingAnnotation() && isMethodExecution()") 
    void beforeRequestMappedMethodExecution(JoinPoint joinPoint) { 
        String method = joinPoint.getSignature().toShortString(); 
        System.out.println("Intercepted: " + method); 
 
        //Now do whatever you need to 
    } 
}