jfinal使用session判断是否登录以及登录超时

利用jfinal的缓存插件验证登录,以及空闲超时退出登录。
未登录直接请求url将被跳转到登录页。

一、登录处理
public class LoginController extends BaseController {

 public void index() {
 }
 public void login() { 
   try {
    Record user = Db.findFirst("select * from sys_user where name = ? and password = ? ", this.getPara("username"), this.getPara("password"));
    if (user != null) {
      this.toMessageJson(200, "登录成功");
      String sid=getSession().getId();
      CacheKit.put("LoginUserCache", sid, user); // 将用户信息保存到缓存,用作超时判断
     }else{
      this.toMessageJson(300, "用户名或密码错误");
     }
         } catch(AuthenticationException e) {
             this.toMessageJson(300, "用户名或密码错误");
         }
 }
}
登录成功后保存user对象到缓存,作为以后判断的依据。注意要用session的id作为缓存的key,确保区分不同终端的请求。

二、拦截所有请求
public class LoginInterceptor implements Interceptor {
 
 @Override
 public void intercept(ActionInvocation ai) {
  Controller ctl=ai.getController();
     
  //判断用户是否登录
  String sid=ctl.getSession().getId();
  Record user=CacheKit.get("LoginUserCache", sid);
  String action=ai.getActionKey();
  if(user!=null || action.indexOf("login")>=0){
   ai.invoke();
  }else{
   ctl.redirect("/login");
  }
 }
}
上面代码中,对所有请求进行拦截,请求路径中带有login的,予以放行。其他的根据sessionid获得cache中存储的user对象,如果为空表示未登录,或登录超时cache清空。需要重新登录,跳转到登录页。
三、注册全局拦截器
public class DemoConfig  extends JFinalConfig{
    。。。。。。
 @Override
 public void configInterceptor(Interceptors me) {
         me.add(new LoginInterceptor()); 
 }    
    。。。。。。
}

四、缓存配置文件
在src目录下编辑ehcache-shiro.xml文件,<ehcache>区块中增加如下内容:
    <cache name="LoginUserCache"
           maxElementsInMemory="10000"
           overflowToDisk="false" //数量过大是否保存至磁盘
           eternal="false" //是否永久保留
           timeToLiveSeconds="6000" //存在时长
           timeToIdleSeconds="60"/>       //空闲保留时长(60s即为登录空闲超时时长)

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值