spring boot实战教程之shiro session过期时间详解
前言
众所周知在springboot内,设置session过期时间只需在application.properties内添加server.session.timeout配置即可。在整合shiro时发现,server.session.timeout设置为7200,但未到2小时就需要重新登录,后来发现是shiro的session已经过期了,shiro的session过期时间并不和server.session.timeout一致,目前是采用filter的方式来进行设置。
ShiroSessionFilter
/** *通过拦截器设置shiroSession过期时间 *@authoryangwk */ publicclassShiroSessionFilterimplementsFilter{ privatestaticLoggerlogger=LoggerFactory.getLogger(ShiroSessionFilter.class); publicListexcludes=newArrayList (); privatelongserverSessionTimeout=180000L;//ms publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainfilterChain)throwsIOException,ServletException{ if(logger.isDebugEnabled()){ logger.debug("shirosessionfilterisopen"); } HttpServletRequestreq=(HttpServletRequest)request; HttpServletResponseresp=(HttpServletResponse)response; if(handleExcludeURL(req,resp)){ filterChain.doFilter(request,response); return; } SubjectcurrentUser=SecurityUtils.getSubject(); if(currentUser.isAuthenticated()){ currentUser.getSession().setTimeout(serverSessionTimeout); } filterChain.doFilter(request,response); } privatebooleanhandleExcludeURL(HttpServletRequestrequest,HttpServletResponseresponse){ if(excludes==null||excludes.isEmpty()){ returnfalse; } Stringurl=request.getServletPath(); for(Stringpattern:excludes){ Patternp=Pattern.compile("^"+pattern); Matcherm=p.matcher(url); if(m.find()){ returntrue; } } returnfalse; } @Override publicvoidinit(FilterConfigfilterConfig)throwsServletException{ if(logger.isDebugEnabled()){ logger.debug("shirosessionfilterinit~~~~~~~~~~~~"); } Stringtemp=filterConfig.getInitParameter("excludes"); if(temp!=null){ String[]url=temp.split(","); for(inti=0;url!=null&&i 注册filter
在被@Configuration注解标注的类内注册ShiroSessionFilter。
@Value("${server.session.timeout}") privateStringserverSessionTimeout; @Bean publicFilterRegistrationBeanshiroSessionFilterRegistrationBean(){ FilterRegistrationBeanfilterRegistrationBean=newFilterRegistrationBean(); filterRegistrationBean.setFilter(newShiroSessionFilter()); filterRegistrationBean.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE); filterRegistrationBean.setEnabled(true); filterRegistrationBean.addUrlPatterns("/*"); MapinitParameters=Maps.newHashMap(); initParameters.put("serverSessionTimeout",serverSessionTimeout); initParameters.put("excludes","/favicon.ico,/img/*,/js/*,/css/*"); filterRegistrationBean.setInitParameters(initParameters); returnfilterRegistrationBean; } 这样当每次请求时,如果用户已登录,就重新设置shirosession有效期,从而和serversession保持了一致。
总结
以上就是这篇文章的全部内容,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。