[JSP study]세션과 쿠키

Noah97·2022년 5월 23일
0

JspStudy

목록 보기
9/18
post-thumbnail

1.세션(Session)

세션이란 서버측의 컨테이너에서 관리되는 정보이다. 세션의 정보는 컨테이너에 접속해서 종료되기 까지(브라우저를 종료할 때까지) 유지되며, 접속 시간에 제한을 두어 일정 시간 응답이 없다면 정보는 더 이상 유지되지 않게 설정이 가능하다. 쿠키같이 클라이언트에 정보가 저장될 경우 데이터가 노출되어 보안적으로 심각한 문제가 발생할 수 있다. 보안이 필요한 정보를 공유하기 위해서는 서버측에서 관리될 수 있는 세션을 이용하는 것이 좋다. 클라이언트와 서버의 연결 정보를 유지하려면 연결이 끊어지지 않고 유지 되어야하므로 세션 기능이 필요하다.

1.1 세션 객체의 메소드

메소드설명
setAttribute(String attrName, Object attrValue)세션 영역에 속성을 생성한다.
removeAttribute(String attrName)파라미터로 지정된 이름의 속성을 제거한다.
getAttribute(String attrName)지정된 이름의 속성 값을 반환한다.
getId()클라이언트의 세션 ID 값을 반환한다.
setMaxInactiveInterval(int seconds)세션의 유지 시간을 설정한다.
getMaxInactiveInterval()세션의 유지 시간을 반환하다.
invalidate()현재의 세션 정보들을 모두 제거한다.

실행 예제
sessionTest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%
	String name;
	if(session.getAttribute("name") != null) {
		name=(String)session.getAttribute("name");
	} else {
		name = "세션 값 없음.";
	}
%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> session Test</title>
</head>
<body>
<h2>세션 테스트</h2>
<input type = "button" onclick = "location.href = 'sessionSet.jsp'" value = "세션 값 저장">
<input type = "button" onclick = "location.href = 'sessionDel.jsp'" value = "세션 값 삭제">
<input type = "button" onclick = "location.href = 'sessionInvalidate.jsp'" value = "세션 초기화">
<h3><%=name %></h3>
</body>
</html>

sessionSet.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%session.setAttribute("name", "Session Test!"); %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
	location.href = "sessionTest.jsp";
</script>
</head>
<body>

</body>
</html>

sessionDel.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%session.removeAttribute("name"); %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
	location.href = "sessionTest.jsp";
</script>
</head>
<body>

</body>
</html>

sessionInvalidate.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%session.invalidate(); %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
	location.href = "sessionTest.jsp";
</script>
</head>
<body>

</body>
</html>

2. 쿠키

쿠키란 클라이언트측에서 관리되는 정보를 의미한다. 세션과의 차이를 비교해보면 세션은 서버 측에서 관리되지만 쿠키는 클라이언트에 정보가 저장된다. 또한 쿠키의 정보는 세션과 달리 브라우저를 종료한다고 해도 생존 기간이 지정되면 생존기간 동안 데이터가 사라지지 않는다. 쿠키는 하드디스크에 파일로 저장되기 때문에 그 파일이 남아있는 한 쿠키는 항상 유지된다. 쿠키는 클라이언트에서 관리되기 때문에 보안적으로 매우 취약한 면을 가지고 있다. 쿠키는 클라이언트에서만 사용될 데이터를 보관하고 그 데이터는 보안적으로 문제를 일으키지 않는 데이터여야 한다.

2.1 쿠키 객체의 생성자 및 메소드

속성설명
setValue(String value)쿠키 값을 설정한다.
setMaxAge(int seconds)쿠키 만료 기간을 지정한다.
getValue()쿠키 값을 얻어온다.
getMaxAge()쿠키 만료 기간을 얻어온다.
getName()쿠키 이름을 얻어온다.

실행 예제
cookieTest1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	Cookie cookie = new Cookie("name", "hongkildong");
	cookie.setMaxAge(600);
	response.addCookie(cookie);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2><%=cookie.getName() %></h2>
<h2><%=cookie.getValue() %></h2>
<h2><%=cookie.getMaxAge() %></h2>
<a href="cookieTest2.jsp">쿠키 값 불러오기</a>
</body>
</html>

cookieTest2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%
	String name = "";
	String value = "";
	String cookie = request.getHeader("Cookie");
	
	if(cookie != null) {
		Cookie cookies[] = request.getCookies();
		
		for(int i = 0; i < cookies.length; i++) {
			if(cookies[i].getName().equals("name")) {
				name = cookies[i].getName();
				value = cookies[i].getValue();
			}
		}
	}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cookie Test</title>
</head>
<body>
<h2>쿠키 이름 = <%=name %></h2>
<h2>쿠키 값 = <%=value %></h2>
</body>
</html>

불러오기 클릭 시 ⬇️

3. 세션을 이용한 로그인 정보 유지

일반 포탈 사이트에 로그인한 후에 브라우저를 종료하거나 오랜 시간 응답이 없을 경우를 제외하면 다른 사이트를 이동하고 다시 돌아오더라도 접속했던 포탈 사이트에 그대로 로그인되어 있는것을 확인할 수 있다. 그 이유는 세션을 사용하여 로그인 정보를 저장해 두었기 때문이다. 사용자가 로그인을 하게 되면 로그인 정보는 서버측 컨테이너에 저장되며, 이 정보를 계속 가지고 있으면서 클라이언트가 로그인 상태를 유지할 수 있게 해준다.

실행 예제
sessionLogin1.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 = "sessionLogin2.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>

sessionLogin2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%session.setAttribute("id", request.getParameter("id")); %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>로그인되었습니다.</h3>
<h3>로그인 아이디 : <%=(String)session.getAttribute("id") %></h3>
<a href="sessionLogout.jsp">로그아웃</a>
</body>
</html>

sessionLogout.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 = "sessionLogin1.jsp">로그인 페이지로 이동</a>
</body>
</html>



3.1 쿠키를 이용한 사용자화면 설정 정보 유지

쿠키는 클라이언트에 저장되어 환경 설정을 유지할 수 있는 기능도 구현할 수 있으며 이 기능은 보안이 필요하지 않으므로 세션보다 쿠키로 사용하는 것이 훨씬 더 효율적이다.

실행 예제

cookieExample1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String language = "korea";
	String cookie = request.getHeader("Cookie");
	
	if(cookie != null) {
		Cookie cookies[] = request.getCookies();
		
		for(int i = 0; i < cookies.length; i++) {
			if(cookies[i].getName().equals("language")) {
				language = cookies[i].getValue();
			}
		}
	}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>쿠키를 이용한 화면 설정 예제</title>
</head>
<body>
<%if(language.equals("korea")) { %>
	<h3>안녕하세요 이것은 쿠키 예제 입니다.</h3>
	<%} else { %>
		<h3>Hello. This is cookie Example</h3>
		<% } %>
		
<form action="cookieExample2.jsp" method = "post">
	<input type = "radio" name = "language" value = "korea"
		<%if(language.equals("korea")) { %> checked <% } %>>한국어 페이지 보기
	<input type = "radio" name = "language" value = "english"
		<%if(language.equals("english")) { %> checked <% } %>> 영어 페이지 보기
	<input type = "submit" value = "전송">
		
</form>
</body>
</html>

cookieExample2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	Cookie cookie = new Cookie("language", request.getParameter("language"));
	cookie.setMaxAge(60*60*24);
	response.addCookie(cookie);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
	location.href = "cookieExample1.jsp";
</script>
</head>
<body>

</body>
</html>


전송 클릭 시 ⬇️

profile
안녕하세요 반갑습니다😊

0개의 댓글