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

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

最佳答案

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

选项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;

这是我如何定义一个控制器方面来拦截所有控制器端点方法的示例:
@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
    }
}

09-27 07:09