实现功能,在登陆状态下浏览器跟服务器一段时间不进行交互,session内部存放的信息将会失效,类似存放在其中的(adminUser)但是依然可以浏览登录后的网页,再跟服务器进行交互才会报错
实现需求:SpringMVC Redis 数据库
1.SpringMVC 进行拦截,
1)session里面有adminUser,则把adminUserId放到redis内部 JedisUtils.setex("keeponline_" + request.getSession().getId(), 60 * 60 * 24, adminUser.getId() + ""); return true;
2)session里面没有adminUser 如果不存在则有可能两种情况,第一次访问服务器或者session过期
进一步判断,Cookie sessionIdCookie = WebUtils.getCookie(request, "JSESSIONID");如果sessionIdCookie==null,则说明第一次访问,return true,
否则的话从redis里面取出当session里面有数据已经存放在redis里面的adminUserId,对应的key为“keeponline”+sessionIdCookie.getValue(),
String oldSessionId = sessionIdCookie.getValue();
String adminUserId = JedisUtils.get("keeponline_" + oldSessionId);然后在数据库进行查找,重新把adminUser添加到session里面进行正常操作
3)配置拦截器,登录,退出不需要进行拦截
相关代码:
package com.rupeng.web.rupengInterceptor;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;
import com.rupeng.pojo.AdminUser;
import com.rupeng.service.AdminUserService;
import com.rupeng.util.JedisUtils;
public class OnlineInterceptor extends HandlerInterceptorAdapter
{
@Autowired
private AdminUserService adminUserService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
{
AdminUser adminUser = (AdminUser) request.getSession().getAttribute("adminUser");
//判断adminUser是否为null,不是则继续往下走,是的话有可能第一次打开浏览器,也有可能seession过期,继续判断
if (adminUser == null)
{
Cookie sessionIdCookie = WebUtils.getCookie(request, "JSESSIONID");
if (sessionIdCookie == null)//如果为null则说明第一次访问
{
return true;
}
//不为null则从redis里面把对应的adminUserId取出来,重新设置到session内进行正常操作
//存放到redis时约定主键为keeponline_sessionIdCookie (keeponline_sessionIdCookie,adminUserId)
String oldSessionId = sessionIdCookie.getValue();
String adminUserId = JedisUtils.get("keeponline_" + oldSessionId);
if (adminUserId == null)
{
return true;
}
adminUser = adminUserService.selectOne(Long.parseLong(adminUserId));
request.getSession().setAttribute("adminUser", adminUser);
return true;
}
JedisUtils.setex("keeponline_" + request.getSession().getId(), 60 * 60 * 24, adminUser.getId() + "");
return true;
}
}
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:mapping path="/subject/*"/>
<mvc:mapping path="/card/*"/>
<mvc:mapping path="/user/*"/>
<mvc:mapping path="/classes/*"/>
<mvc:mapping path="/permission/*"/>
<mvc:mapping path="/*"/>
<mvc:exclude-mapping path="/adminUser/login.do"/>
<mvc:exclude-mapping path="/adminUser/logout.do"/>
<bean class="com.rupeng.web.rupengInterceptor.OnlineInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>