[JSP study] 세션과 쿠키를 이용한 로그인 예제 구현

Noah97·2022년 5월 27일
0

JspStudy

목록 보기
12/18
post-thumbnail

📝세션과 쿠키를 이용한 로그인 예제

쿠키를 이용하여 id별로 방문횟수를 체크하여 주는 예제이다.
login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Session Login</title>
<style>
	#loginArea {
		width : 400px;
		margin : auto;
		border : 1px solid black;
	}
	table {
		margin : auto;
	}
	td {
		text-align : center;
	}
</style>
</head>
<body>
<section id = "loginArea">
	<form action = "main.jsp" method = "post">
		<table>
			<tr>
				<td><label for = "id">아이디 :</label></td>
				<td><input type = "text" name = "id" id = "id"></td>
			</tr>
			<tr>
				<td><label for = "pass">비밀번호 :</label></td>
				<td><input type = "password" name = "pass" id = "pass"></td>
			</tr>
			<tr>
				 <td colspan="2"><input type = "submit" value = "로그인">
				 <input type = "reset" value = "다시작성"></td>
			</tr>
		</table>
	</form>
</section>
</body>
</html>

실행 화면 ⬇

main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%
session.setAttribute("id", request.getParameter("id"));
%>
<%
Cookie[] cookies = request.getCookies();
String id = (String) session.getAttribute("id");
int visitCount = 0;
for (Cookie cookie : cookies) {
	if (cookie.getName().equals(id)) {
		visitCount = Integer.parseInt(cookie.getValue());
	}
}
%>
<%
visitCount++;
Cookie cookie = new Cookie(id, "1");
Cookie c[] = request.getCookies();
for (int i = 0; i < c.length; i++) {
	if (c[i].getName().equals(id)) {
		cookie.setValue(Integer.toString(Integer.parseInt(c[i].getValue()) + 1));
	}
}
response.addCookie(cookie);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h3><%=(String) session.getAttribute("id")%>님 반갑습니다.
	</h3>
	<h3><%=visitCount%>번째 방문입니다.
	</h3>
	<a href="logout.jsp">로그아웃</a>
</body>
</html>

실행 화면 ⬇
로그아웃 버튼 누를 시 로그아웃 페이지로 변경

logout.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%session.removeAttribute("id"); %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>로그아웃 되었습니다.</h3>
<a href = "login.jsp">로그인</a>
</body>
</html>

로그인 버튼 누를 시 다시 로그인 화면으로 돌아간다.

핵심 코드

<%
session.setAttribute("id", request.getParameter("id"));
%>
<%
Cookie[] cookies = request.getCookies(); //쿠키 값들을 배열로 가져온다.
String id = (String) session.getAttribute("id"); id라는 속성의 값이 null값이 반환되지 않았으면 즉, id라는 이름의 속성 값이 세션 영역에 저장되어 있으면 저장된 속성 값을 id 변수에 String형으로 할당한다.
int visitCount = 0; //방문 횟수를 체크
for (Cookie cookie : cookies) {
	if (cookie.getName().equals(id)) { 
		visitCount = Integer.parseInt(cookie.getValue());
	} //쿠키로 부터 얻어온 값을 visitCount에 int 형으로 대입한다.
}
%>
<%
visitCount++; //visitCount 처음에 1 증가
Cookie cookie = new Cookie(id, "1"); //쿠키 객체를 생성하고 id에 1을 넣어준다.
Cookie c[] = request.getCookies(); //c배열에 존재하는 쿠키 값들을 가져온다.
for (int i = 0; i < c.length; i++) {
	if (c[i].getName().equals(id)) {
		cookie.setValue(Integer.toString(Integer.parseInt(c[i].getValue()) + 1)); //c가 for문을 돌면서 id와 값이 같으면 cookie의 값을 지정해준다. 
	}
}
response.addCookie(cookie); //응답 헤더에 쿠키를 추가해 준다.
%>
profile
안녕하세요 반갑습니다😊

0개의 댓글