java httpssession有效吗?
我在 tomcat 中使用 java servlet API。
我将用户名和带有属性用户名的 httpsession 保存在哈希表中,我想知道是否有办法检查 httpsession 是否有效。
我尝试过:
try {
String user = httpSession.getAttribute("username")
return "is valid";
} catch (IllegalStateException e) {
return "is not valid";
}
如果我不希望“已登录”用户从多个地方连接,我该怎么办?如果我仅控制是否创建新会话,我无法知道他是否已与另一个会话连接。
I'm using the java servlet API in tomcat.
I save in a hash table the username and the httpsession with the attribute username and I would like to know if there is a way to check if the httpsession is valid.
I've tried:
try {
String user = httpSession.getAttribute("username")
return "is valid";
} catch (IllegalStateException e) {
return "is not valid";
}
What can I do if I don't want that a "logged" user connect from more than one place? If I control only if I create a new session, I can't know if he was connected already with another session.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
无需将 httpSession 存储在您自己的哈希中。
查看 HttpServletRequest 的 API。如果您查看方法 getSession (Boolean x)(传递 false,因此不会创建新会话)将确定会话是否有效。
这是一个示例
附带说明,如果我正确阅读了您的问题并且您将信息存储在自己的映射中,则需要小心不要造成内存泄漏并清除哈希表中的条目你自己。
No need to store the httpSession in your own hash.
Look at the API for the HttpServletRequest. If you look at method getSession(Boolean x) (pass false so it doesn't create a new session) will determine if the session is valid.
Here is an example
On a side note, If I read your question properly and you are storing the information in your own map, you need to be careful that you don't create a memory leak and are clearing the entries out of the hash table yourself.
我同意肖恩的观点。我要补充的是,这种类型的检查的一个好习惯是使用过滤器
请参见此处 Servlet Filter
只需将 Sean 编写的代码放入 Filter 中即可。在 web.xml 中定义过滤器,每次收到请求时,过滤器都会执行。
这样您就可以验证用户是否经过身份验证。不会弄乱您的 servlet 代码。
I agree with Sean. I will add that a good practice for this type of checking is to use a Filter
See here Servlet Filter
Just take the code Sean have written and put it in a Filter instead. Define you filter in the web.xml and every time a request come in, the filter will execute.
This way you can validate if the user is auth. without cluttering your servlet code.
您应该查看 servlet 上的
HttpServletRequest
,并检查其上的isRequestedSessionIdValid()
,而不是检查保存的会话是否有效。在 servlet 中工作时,您始终可以从Request
获取Session
,而不是将其保存到哈希表中。Rather than checking if a saved session is valid, you should be looking at the
HttpServletRequest
on your servlet, and checkingisRequestedSessionIdValid()
on that. When working in servlets you can always getSession
from theRequest
, rather than saving it to a hash table.