mat_boy
mat_boy

Reputation: 13666

Accessing HttpSession in a ControllerAdvice in a SpringBoot application

I'd like to set some default values in the session in a SpringBoot application. Ideally, I was thinking to use a class annotated with @ControllerAdvice to set the default values. This is useful, especially because the code snippet must be executed for all the pages.

Is there a way to access the HttpSession in a class annotated with @ControllerAdvice?

Upvotes: 5

Views: 7221

Answers (2)

pczeus
pczeus

Reputation: 7867

You can get the session from within your @ControllerAdvice, using:

Option 1:

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

HttpSession session = requeset.getSession(true);//true will create if necessary

Option 2:

@Autowired(required=true)
private HttpServletRequest request;

Option 3:

@Context
private HttpServletRequest request;

Here is an example of how I have devined a Controller aspect that intercepts all controller endpoint methods:

@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
    }
}

Upvotes: 4

JSONStatham
JSONStatham

Reputation: 373

I would recommend you to use Spring Interceptors rather then @ControllerAdvice. Later you can easily customize behaviour with Interceptor mappings.

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

@ControllerAdvice really shines, when you want to handle some exceptions globally.

Upvotes: 0

Related Questions