2017-04-11 37 views
0

我有一个logout.jsp页面,这是用来无效会话,这里不是取消设置会话可以是它的内容:在Java Servlet的

session.invalidate(); 
response.sendRedirect("login.jsp"); 

在我profile.jsp页我要检查是否会话变量设置与否,并取决于允许用户浏览网页或重定向到登录页面(如果会话变量未设置)

if(request.getSession(false)==null){ 
    response.sendRedirect("login.jsp"); 
} 

但问题是,这是不工作作为即使在没有用户登录的情况下,也可以直接从地址栏打开profile.jsp页面,该页面将以o打开ut重定向到登录页面。进一步在打印request.getSession(false)我得到输出[email protected]。我不知道这是什么,也没有在互联网上发现它。那么如何解决这个问题。

编辑:

类“用户”,其对象我使用的会话变量实现了系列化,所以,可以说是我所面临的问题的原因。

我没有被允许评论,所以我在这里提到它。 我使用铬接受cookie ....进一步我在Microsoft边缘尝试相同,但它仍然是相同的

+0

一个JSP会自动创建一个会话,除非您告诉它不要创建一个会话。通常我们在会话中放置一个属性并检查是否设置了该属性。 – rickz

+0

是的,我也尝试过:'if(session.getAttribute(“user”)== null){ \t response.sendRedirect(“login.jsp”);} System.out.println(session.getAttribute “user”));'这里用户是会话变量属性,控制台输出是'mypack.user @ 1ad20a7',其中mypack是包的名称我有一个'user'命名的类。我使用的对象是会话变量 – Sourajit

+0

这不是重定向 – Sourajit

回答

0

我假设你已经创建了登录和注销的servlet,然后从相应的servlet,你可以重定向页面: 这可能是您的登录servlet代码:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

    String email = request.getParameter("email"); 
    String password = request.getParameter("password"); 
    HttpSession session = request.getSession(); 
    session.setAttribute("userName", email); 
    session.setAttribute("password", password); 
    getServletContext().getRequestDispatcher("/profile.jsp").forward(request, 
    response); 
    } 

这可能是你的profile.jsp网页代码来检查会话:

<% 
if(!(request.getSession(true).getAttribute("userName").toString()).isEmpty()){ 
    String firstName = (String)request.getAttribute("firstName"); 
String lastName = (String)request.getAttribute("lastName"); 
}else{%> 
<jsp:forward page = "Login.jsp" /> 
<% }%> 

从登出页面你可以发送请求lo goutservlet。而且,这可能是您的logoutservlet代码:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    response.setContentType("text/html"); 
    PrintWriter out = response.getWriter(); 
    HttpSession session = request.getSession(); 
    session.invalidate(); 
    out.println("Logout Successful"); 
    out.println("Username : "+session.getAttribute("userName")); 
    out.println("Password : "+session.getAttribute("password")); 

} 

然后当我正在从会话我得到空值对于这些领域的凭据后。

+0

'<%= request。getSession(true).getAttribute(“userName”)。toString()。isEmpty()%>'返回false ...我尝试了上面的方法,并在我的注销页面中request.getSession(false)'返回null,但是在打开profile.jsp页面(没有登录)它返回true ...如果你想看到我的任何特定的文件,你可以提到我会在这里添加它。 – Sourajit