利用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即为登录空闲超时时长)