How to use cookie to log out from website

1. login.jsp to get the username and password from user

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<form action="<%= request.getContextPath()%>/Controller" method="post">

	<!-- we display the username and password and submit them to Controller -->
	Username: <input type="text" name="username" ><br/>
	Password: <input type="password" name="password"><br/>
	<input type="submit" value="submit">
	
</form>

</body>
</html>

2. Controller servlet to handle the information from user and direct user into memberArea page

package cook.xxxxxx;

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 Controller
 */
@WebServlet("/Controller")
public class Controller extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public Controller() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// get information from form, username and password
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		// if else sentence to handle different situiations
		if(username.equals("James") && password.equals("123")) {
			// first we get the session and set all sessions to be invalidate
			request.getSession().invalidate();
			// then we create new session and set its active time for 300 seconds
			HttpSession newSession = request.getSession(true);
			newSession.setMaxInactiveInterval(300);
			// create a cookie cUsernameCookie
			Cookie cUsernameCookie = new Cookie("username", username);
			response.addCookie(cUsernameCookie);
			// enter into the memberArea.jsp
			response.sendRedirect("memberArea.jsp");
		} else {
			// enter into the login.jsp
			response.sendRedirect("login.jsp");
		}
	}

}

3. Then we can enter into the memberArea page

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Member Area</title>
</head>
<body>

	<%
	String username = null, sessionID = null;
	Cookie[] cookies = request.getCookies();
	if(cookies != null){
		for(Cookie cookie : cookies){
			if(cookie.getName().equals("username") ){
				username = cookie.getValue();
			}
			if(cookie.getName().equals("JSESSIONID")){
				sessionID = cookie.getValue();
			}
		}
	}
	if(sessionID == null || username == null){
		response.sendRedirect("login.jsp");
	}
	%>
	
	Username : <%= username %><br>
	SessionID : <%= sessionID %><br>
	We entered into the member area !!! <br>

	<!-- add another form to handle the logout of the page -->
	<!-- use the  MemberAreaController to handle the form information to logout-->
	<form action="<%= request.getContextPath()%>/MemberAreaController" method="get">
    <input type="hidden" name="action" value="destroy">
    <input type="submit" value="logout">
    </form>
    
</body>
</html>

And in this memberArea page we use another form to handle the logout function, and we use another servlet named MemberAreaController to handle the get the action = destroy from this form

4. MemberAreaController servlet to handle logout and destroy the session and cookies

package cook.xxxxxx;

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;

/**
 * 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#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// first we get the action string from the request by request.getParameter("action")
		String action = request.getParameter("action");
		// if the action is destroy, then we handle logout
		switch (action) {
		case "destroy":
			// we need to destroy this session
			request.getSession().invalidate();	
			// and set all the cookies to be null
			Cookie[] cookies = request.getCookies();
			for(Cookie cookie: cookies) {
				// we need to set the cookie which name is username to be null
				// and max age to be 0
				if(cookie.getName().equals("username")) {
					cookie.setValue(null); // set to be null
					cookie.setMaxAge(0); // set the max age to be 0
					response.addCookie(cookie);
				}
			}
			// then we redirect the page to login.jsp
			response.sendRedirect("login.jsp");
			break;

		default:
			break;
		}
	}
}

5. How do this program work?
login page
After we login the page and entered into the MemberArea page
Then we logout from above page and destroy the data of that login
6. Notation
If we don’t handle the cookies which names username by the following codes in the MemberAreaController servlet, problem will occur.
When we clicked on the logout button, we still are not logout because we can still enter into the link http://localhost:8080/cook/memberArea.jsp to directly enter into the memberArea page, which is not good
The reason is that we create a cookie named username, so if we don’t handle this cookie, when the old session is invalidated, a new session with a new sessionId will created.

			Cookie[] cookies = request.getCookies();
			for(Cookie cookie: cookies) {
				// we need to set the cookie which name is username to be null
				// and max age to be 0
				if(cookie.getName().equals("username")) {
					cookie.setValue(null); // set to be null
					cookie.setMaxAge(0); // set the max age to be 0
					response.addCookie(cookie);
				}
			}

Thus we need to invalidate the cookie named username to be null and make its setMaxAge to be 0
Actually, logout using cookie is not a good idea, we can handle logout using session attribute later.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值