메서드

메서드 설명
new Cookie(name, value) 쿠키 생성 (이름, 값 설정)
cookie.setMaxAge(time) 쿠키의 유지 시간 설정 (초 단위, 0이면 삭제)
cookie.setPath(path) 쿠키의 유효 범위 지정
response.addCookie(cookie) 클라이언트에 쿠키 전송
request.getCookies() 클라이언트가 전송한 쿠키 가져오기

JSP 쿠키 로그인 예제

1️⃣ 로그인 페이지 (cookie.jsp)

사용자가 ID와 비밀번호를 입력하면 createCookie.jsp로 전송됨

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>쿠키 로그인</title>
</head>
<body>
	<h3>1. 쿠키 로그인 실습</h3>

	<h4>쿠키 로그인</h4>
	<form action="./proc/createCookie.jsp" method="post">
		<input type="text" name="uid" placeholder="아이디 입력"><br>
		<input type="password" name="pass" placeholder="비밀번호 입력"><br>
		<input type="submit" value="로그인">
	</form>
</body>
</html>

2️⃣ 쿠키 생성 (createCookie.jsp)

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>쿠키 생성</title>
</head>
<body>
	<h3>쿠키 생성</h3>
	<%
		// 데이터 수신
		String uid = request.getParameter("uid");
		String pass = request.getParameter("pass");

		// 프로젝트 컨텍스트 경로 구하기
		String ctxPath = application.getContextPath();

		// 아이디가 abc, 비밀번호가 1234이면 로그인 성공
		if(uid.equals("abc") && pass.equals("1234")){

			// 쿠키 생성 (이름: "username", 값: uid)
			Cookie cookie = new Cookie("username", uid);
			cookie.setMaxAge(60 * 3); // 3분 동안 유지
			cookie.setPath(ctxPath); // 프로젝트 내에서만 유효

			// 클라이언트에 쿠키 저장
			response.addCookie(cookie);

			// 로그인 성공 페이지 이동
			response.sendRedirect("./successLogin.jsp");
		} else {
			// 로그인 실패 페이지 이동
			response.sendRedirect("./failLogin.jsp");
		}
	%>
</body>
</html>

3️⃣ 로그인 성공 (successLogin.jsp)

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
	// 쿠키 수신
	Cookie[] cookies = request.getCookies();
	String username = null;

	for(Cookie cookie : cookies){
		if(cookie.getName().equals("username")){
			username = cookie.getValue();
		}
	}
%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>로그인 성공</title>
</head>
<body>
	<h3>로그인 성공</h3>
	<%= username %>님 반갑습니다.
	<a href="./logoutCookie.jsp">로그아웃</a>
</body>
</html>

4️⃣ 로그인 실패 (failLogin.jsp)