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

时间:2016-04-09 17:31:49

标签: java session spring-boot

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

有没有办法访问使用HttpSession注释的班级中的@ControllerAdvice

2 个答案:

答案 0 :(得分:2)

您可以使用以下内容从@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;

以下是我如何设计一个拦截所有控制器端点方法的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
    }
}

答案 1 :(得分:0)

我建议你使用Spring Interceptors而不是@ControllerAdvice。 稍后,您可以使用Interceptor映射轻松自定义行为。

http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-handlermapping-interceptor

@ControllerAdvice真的很棒,当你想要全局处理一些异常时。