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
?
No prior knowledge of Spring Session or Apache Geode is required to utilize HTTP Session State Caching in your Spring Boot applications.
Spring Session provides transparent integration with HttpSession . This means that developers can switch the HttpSession implementation out with an implementation that is backed by Spring Session.
To work with interceptor, you need to create @Component class that supports it and it should implement the HandlerInterceptor interface. preHandle() method − This is used to perform operations before sending the request to the controller. This method should return true to return the response to the client.
@ControllerAdvice is a specialization of the @Component annotation which allows to handle exceptions across the whole application in one global handling component. It can be viewed as an interceptor of exceptions thrown by methods annotated with @RequestMapping and similar.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With