Wednesday, February 26, 2020

Invalidate Session on Spring @ControllerAdvice

Problem:

When some exception comes in spring web application, some times we have to redirect the page some exception jsp/html page .
we have to fix this problem in ControllerAdvice Class.

Solution:

        
    @ExceptionHandler(ResourceAccessException.class)
    public ModelAndView handleResourceAccessException(ResourceAccessException ex,HttpServletRequest request) {
      LOG.error(START);
      HttpSession session= request.getSession(false);
        SecurityContextHolder.clearContext();
         if(session != null) {
             session.invalidate();
         }
        ModelAndView model = new ModelAndView();
        LOG.error(MESSAGE,ex.getMessage());
        model.setViewName("generic_page");
        LOG.error(END);
        return model;
    }
  • we get the session Object from HttpServletRequest object and checks the null condition and after that we have invalidated the session.
  • Important point

    is that we have write this statment : SecurityContextHolder.clearContext(); otherwise Spring Security will not identify our session invalidation.

No comments:

Post a Comment

Recent Post

Databricks Delta table merge Example

here's some sample code that demonstrates a merge operation on a Delta table using PySpark:   from pyspark.sql import SparkSession # cre...