Using session attribute to handle logout from a page

IF we only need to handle login and logout, cookie is not a good idea, we can handle login and logout by using session attribute
For example when we click the logout button, the servlet to handle the logout function will get the action is destroy and then invalidate the current session and direct user into another page - login.jsp page. If user want to enter the member page again, he will be asked to enter the username and password once again.
However, if we use cookie to handle logout, we need to handle the cookie, we need to set it to be null and set the max age to be 0m which is not a good idea for complexity.
The following example show us how to handle logout using session attribute:

First, we need to create a login.jsp page

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
	<form action="<%= request.getContextPath()%>/SiteController" method="post">
		Username: <input type="text" name="username" ><br/>
		Password: <input type="password" name="password"><br/>
		<input type="submit" value="submit">
	</form>
</body>
</html>

Second, we need to create a Controller servlet to handle the login and direct the user into the member page

package org.studyeasy.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class SiteController
 */
@WebServlet("/SiteController")
public class SiteController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SiteController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		// get username and password from login page
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		// if username is studyeasy and password is love
		if(username.equals("studyeasy") && password.equals("Love")) {
			//Invalidating session if any
			request.getSession().invalidate();
			// get the new session
			HttpSession newSession = request.getSession(true);
			// set it to be 300 
		    newSession.setMaxInactiveInterval(300);
		    // set the newSession's attribute username to be username
		    newSession.setAttribute("username", username);
		    // direct user to memberArea page
		    response.sendRedirect("memberArea.jsp");
		}else {
			// direct user to login page
			response.sendRedirect("login.jsp");
		}
	}
}

And in this servlet we set the session attribute username to be username string
The memberArea.jsp codes is as following

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Member Area</title>
</head>
<body>

	<!-- get username and sessionID -->
	<%
		String username = null, sessionID = null;
		// if session's attribute username is null, direct it to login page
	    if(request.getSession().getAttribute("username") == null){
	    	response.sendRedirect("login.jsp");
	    }else{ // else set the username and sessionID
	    	username = request.getSession().getAttribute("username").toString();
	    	sessionID = request.getSession().getId();
	    }
	%>
	
	<!-- show the username and session ID -->
	Username:<%=username%><br /> 
	Current session:<%=sessionID%><br /> 
	memberArea!!
	
	<!-- logout -->
    <form action="<%= request.getContextPath()%>/MemberAreaController" method="get">
    	<input type="hidden" name="action" value="destroy">
    	<input type="submit" value="logout">
    </form>
    
</body>
</html>

In this memberArea page we use request.getSession().getAttribute(“username”) to get the username and then if we click the logout button we will logout the back end will be handle by servlet , the following is the code for the servlet

package org.studyeasy.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class MemberAreaController
 */
@WebServlet("/MemberAreaController")
public class MemberAreaController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public MemberAreaController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String action = request.getParameter("action");
		switch (action) {
		case "destroy":
			request.getSession().invalidate();	
			response.sendRedirect("login.jsp");
			break;

		default:
			break;
		}
	}
}

In this servlet we invalidate the current session and that’s all we need to do to logout, and we don’t need to handle cookies, that’s good!!!
request.getSession().invalidate() can invalidate the current session and we logout successfully

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值