基于计时器任务的注销给我带来了问题
在这个网站中,我需要一个可以在 10 分钟后让用户注销的系统。 为了登录,我使用一个简单的过程来插入用户(在我的例子中称为“Lid”)实例,注销会使会话无效,此外,当用户登录计时器启动内的计时器任务时, 10 分钟后会话失效。
这是代码:
MyTask task = null;
private void setCurrent(String key, Object o) {
getRequest().getSession().setAttribute(key, o);
}
private <T> T getCurrent(String key) {
T value = (T) getRequest().getSession().getAttribute(key);
return value;
}
public void logIn(Lid lid) {
setCurrent("lid", lid);
Timer timer = new Timer();
task = new MyTask(getRequest().getSession());
System.out.println(task.toString());
timer.schedule(task,10*60*1000);
}
public void logOut() {
task.cancel();
getRequest().getSession().invalidate();
}
这是 MyTask 代码:
public class MyTask extends TimerTask {
HttpSession session = null;
public MyTask(HttpSession session) {
this.session=session;
}
@Override
public void run() {
session.invalidate();
}
}
问题是,当我自愿注销时,它会抛出异常,因为它说 task
变量为 null
,并且因此无法在 task
变量上调用 cancel()
。
但我不明白,登录变量实例化后,它不是null
。
您对此有什么建议吗? 谢谢
In this website I need a system that logs the user out after 10 minutes.
In order to login I use a simple procedure of inserting a user (in my case called Lid
) instance, and the logout invalidates the session, additionally, when the user logs in a timertask within a timer starts, and after 10 minutes invalidates the session.
Here is the code:
MyTask task = null;
private void setCurrent(String key, Object o) {
getRequest().getSession().setAttribute(key, o);
}
private <T> T getCurrent(String key) {
T value = (T) getRequest().getSession().getAttribute(key);
return value;
}
public void logIn(Lid lid) {
setCurrent("lid", lid);
Timer timer = new Timer();
task = new MyTask(getRequest().getSession());
System.out.println(task.toString());
timer.schedule(task,10*60*1000);
}
public void logOut() {
task.cancel();
getRequest().getSession().invalidate();
}
This is the MyTask code:
public class MyTask extends TimerTask {
HttpSession session = null;
public MyTask(HttpSession session) {
this.session=session;
}
@Override
public void run() {
session.invalidate();
}
}
The problem is that when I voluntarily log out, it throws an exception because it says that the task
variable is null
, and so it becomes not possible to call cancel()
on the task
variable.
But I don't get it, after logging in the variable is instantiated, its not null
.
Do you have some advise about this?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不让 Web 容器为您处理会话超时呢?如果您将以下代码放入 web.xml 中,所有非活动会话将在 10 分钟后过期:
Why not just let the web container handle session time-out for you? If you put below code in your web.xml all inactive sessions will expire in 10 minutes: