1

我是 Spring 新手,在SpringTomcat中开发动态 Web 应用程序,出于某种原因
,我没有使用Spring Security。我想阻止用户访问 已经在会话中 的登录页面。这是我的代码:

@Controller  
@RequestMapping("/login")  
@SessionAttributes("userAuthenticator")  
public class LoginController {  

    @RequestMapping(method = RequestMethod.GET)  
    public String showLogin(ModelMap model, HttpServletRequest request) {  
    System.out.println("Current Session: " + request.getSession(false));  

    if (request.getSession(false) == null) {  
    System.out.println("This means a new user wants to access the login page");  
    return "login";  
    }  

    else{  
    //means the user is already in session.So move him to another page say display.jsp  
    //actually I have done here with some other checking like getUserName() from   
    the model "UserAuthenticator" and if its again null redirect to login page.  
    }  

现在忘记其他部分。当我
第一次在浏览器中输入 URL 时: ..../AccountCreation/login.htm
控制台输出:

Current Session: null  
This means a new user wants to access the login page  

看起来很正常,因为新用户正在访问该页面(登录页面也会出现)。

但是当我重新输入URL 甚至刷新页面时,控制台输出就会出现:

Current Session: org.apache.catalina.session.StandardSessionFacade@511e0a  

那个会话是从哪里来的
(出于这个原因,在我的其他部分我得到:“网页有一个重定向循环”在我的浏览器中)

谁能建议我在不使用Spring Security的情况下实现我的目标的方法?
这对我来说现在非常需要......

谢谢...

4

3 回答 3

2

您可以使用会话变量。

HttpSession ses=request.getSession(false);
if(ses.getAttribute("sessionVar") == null)
     //show login page
else
     // don't show login page

设置会话变量:

 HttpSession ses=request.getSession();
 ses.setAttribute("sessionVar","someValueToShowSession");
于 2012-05-25T10:53:00.593 回答
1

一旦用户向页面发出第一个请求,会话就会开始。所以第二次访问总是会给出一个有效的会话。

如果您想检查他是否是经过身份验证的用户,那么您需要在会话中放置一些标志/值。类似于 userId 的东西。你可以检查一下

如果在会话中设置了 userId -> 有效用户 -> 重定向。

如果用户 ID 未在会话中设置 -> 未登录用户 -> 允许登录页面。

于 2012-05-25T10:50:59.097 回答
0

这只是预期的行为。当您第一次登录时,会创建一个会话并将 jsessionid cookie 存储在浏览器中。除非您使用 session.invalidate() 使会话无效或会话由于会话超时而过期,否则 HttpSession 将可用于该浏览器窗口。

如果您想通过输入登录页面 url 来限制已经登录的用户查看登录页面,然后创建一个拦截器并检查用户是否已经登录。如果用户已经登录然后将他重定向到主页...否则让他去登录页面。

于 2012-05-25T11:26:08.563 回答