为什么会话不为空
我使用以下代码将用户传送到欢迎页面(如果他们已经登录),或者返回到登录页面(如果他们还没有登录)。
HttpSession session = request.getSession(false);
if(session == null){
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}else{
//User already logged in. Send to home.
response.sendRedirect("Welcome");
}
第一次,它工作得很好,但是如果我重新加载页面,即使它将用户发送到欢迎页面,也不可避免地向我发送回 500 错误,因为该页面上的某些元素无法加载,因为用户登录代码有没有被处决。
即使重新加载页面时未声明 request.getSession(true) ,会话也会自动启动吗?有办法防止这种情况吗?
I am using the following code to delivery the user to a Welcome page if they are already logged in, or back to the login page if they are not.
HttpSession session = request.getSession(false);
if(session == null){
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}else{
//User already logged in. Send to home.
response.sendRedirect("Welcome");
}
First time around, it works fine, but if I reload the page even once it sends the user to the welcome page and inevitably sends me back a 500 error because there are elements on that page that cannot be loaded because the user log in code has not been executed.
Does a session get started automatically even if request.getSession(true) is not declared when a page is reloaded? Is there a way to prevent this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
会话可能是在转发到
login.jsp
时创建的。这是必要的,因为必须将用户分配给未经身份验证的请求,然后对其进行身份验证。如果您想根据用户是否登录进行重定向,请使用SessionContext
的getCallerPrincipal
。有关详细信息,请查看这篇(有些旧,但仍然相关)文章
Probably the session is being created upon forwarding to
login.jsp
. That's necessary because the user has to be assigned to an unauthenticated request and then authenticate it. If you want to redirect based on whether the user is logged in or not, useSessionContext
'sgetCallerPrincipal
.For more info, check this (somewhat old, but still relevant) article
如果没有当前会话,
request.getSession(false)
方法将返回 null。我建议也比较一个密钥。请看看这个线程。
The method
request.getSession(false)
returns null if there is no current session. I suggest to compare a key too.Please take a look at this threads.