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

mat*_*boy 5 java session spring-boot

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

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

pcz*_*eus 4

您可以使用以下方法从 @ControllerAdvice 中获取会话:

选项1:

 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

HttpSession session = requeset.getSession(true);//true will create if necessary
Run Code Online (Sandbox Code Playgroud)

选项2:

@Autowired(required=true)
private HttpServletRequest request;
Run Code Online (Sandbox Code Playgroud)

选项 3:

@Context
private HttpServletRequest request;
Run Code Online (Sandbox Code Playgroud)

以下是我如何设计拦截所有控制器端点方法的控制器方面的示例:

@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
    }
}
Run Code Online (Sandbox Code Playgroud)