Springboot integration (10) - Intercepter

Springboot Integration ( 10 ) - Intercepter

This section describes the application scenarios of two interceptors: providing session initialization and recording system logs for the Shiro RememberMe function

Provides session initialization for Shiro RememberMe functionality

The previous section describes the configuration of shiro , and the rememberMe function of shiro is configured in the last part , but there is actually a small problem left: when we log in, we know that shiro will call the doGetAuthenticationInfo method of MyShiroRealm , look back at this method, you You will find that session initialization is done in this method. And once we use the rememberMe function, this method will not be adjusted, then the problem comes, the session cannot be initialized. How to solve this problem? One way to do this is to use an intercepter , as follows:

1. Write SessionIntercepter

@Component

publicclass SessionInterceptor implements HandlerInterceptor {

    privatefinal Log LOG = LogFactory.getLog(SessionInterceptor.class);

 

    @Resource

    private UserService userInfoService;

 

    @Override

    publicboolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        LOG.info("---preHandle---");

        System.out.println(request.getContextPath());

        Subject currentUser = SecurityUtils.getSubject();

        / / Determine that the user is automatically logged in through the remember me function , and the session is invalid at this time

        if (!currentUser.isAuthenticated() && currentUser.isRemembered()) {

            Session session = currentUser.getSession();

            SysUser userInfo = (SysUser) currentUser.getPrincipal();

            session.setAttribute("userId", userInfo.getId());

            session.setAttribute("user", userInfo);

        }

        returntrue;

    }

 

    @Override

    publicvoid postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,

            ModelAndView modelAndView) throws Exception {

        LOG.info("---postHandle---");

    }

 

    @Override

    publicvoid afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,

            Object o, Exception e) throws Exception {

        LOG.info("---afterCompletion---");

    }

}

2. Configure SessionIntersepter in MyWebAppConfigurer

    @Resource

    private SessionInterceptor sessionInterceptor;

 

    /**

     * Interceptor

     *

     */

    @Override

    publicvoid addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(sessionInterceptor).addPathPatterns("/**").excludePathPatterns("/user/login");

        super.addInterceptors(registry);

    }

3. Access the session in the Controller . Just find a controller to access the session , just use indexController . By the way, how to use the session in shiro :

        Subject currentUser = SecurityUtils.getSubject();

        Session session = currentUser.getSession();

        System.out.println(session.getAttribute("user"));



 

4. Test

You can try not to join the SessionIntercepter first , that is, comment out the following line of code

//               registry.addInterceptor(sessionInterceptor).addPathPatterns("/**").excludePathPatterns("/user/login");

此时测试会发现后台打印的session值为null

加入SessionIntercepter,再测session值正常打印

记录系统日志

记录系统日志的意义就不多赘述了,直接说实现

1. 编写LogIntercepter

@Component

publicclass LogInterceptor implements HandlerInterceptor {

 

    @Override

    publicboolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)

            throws Exception {

        returntrue;

    }

 

    @Override

    publicvoid postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,

            ModelAndView modelAndView) throws Exception {

    }

 

    @Override

    publicvoid afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)

            throws Exception {

 

        // 保存日志到数据库的逻辑,根据实际情况自行实现

        // LogService.saveLog(request, handler, ex, null);

 

        System.out.println("HOST : " + request.getRemoteHost());

        System.out.println("URI : " + request.getRequestURI());

        System.out.println("ParamMap : " + request.getParameterMap());

    }

}

 

2. MyWebAppConfigurer中配置LogIntersepter

    @Resource

    private LogInterceptor logInterceptor;

 

    registry.addInterceptor(logInterceptor).addPathPatterns("/**");

 

 

3. 测试,启动项目,访问任意url,后台都会打印LogIntercepter中设置的信息

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326073230&siteId=291194637