세션(Session)이란?
내장 객체로서 브라우저마다 한 개씩 존재하고, 고유한 SessionID 생성 후 정보를 추출한다.
세션(Session) 장단점
- JSP에서만 접근할 수 있기 때문에 보안성이 좋다.
- 기본적으로 서버의 스펙이 좋기때문에 저장 용량의 한계가 거의 없다.
- 서버에 데이터를 저장하므로 서버에 부하가 걸릴 수 있다.
▶ 쿠키보다 세션을 쓰는 것이 더 안정적이다. 다만, 세션에 저장할 공간이 부족할 경우 쿠키를 사용하자.
세션(Session) 값 저장하기
session.setAttribute(이름, 값);
내장 객체 session의 setAttribute 메소드를 통해 값을 저장할 수 있다.
세션(Session) 값 가져오기
session.getAttribute(이름)
내장 객체 session의 getAttribute 메소드를 통해 값을 가져올 수 있다.
이때 이름은 setAttribute에서 설정한 이름과 같은 값을 가져온다.
세션(Session) 삭제하기
// 특정 이름의 세션 삭제
session.removeAttribute(이름);
// 모든 세션 삭제
session.invalidate()
내장 객체 session의 removeAttribute 메소드를 통해 특정 이름의 세션을 삭제할 수 있다.
만약, 모든 세션을 삭제하고 싶다면 invalidate 메소드를 사용하면 된다.
세션(Session) 예제
세션(Session)을 사용하여 로그인한 id를 표시해주는 간단한 예제를 해보자.
- login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인</title>
</head>
<body>
<input type="hidden" name="type" id="type" value="<%=request.getParameter("type")%>">
<form action="login_ok.jsp" name="loginForm" method="post">
<p>
<label>
아이디 : <input type="text" name="id">
</label>
</p>
<p>
<label>
비밀번호 : <input type="password" name="password">
</label>
</p>
<p>
<input type="button" value="로그인" onclick="login()">
</p>
</form>
</body>
<script>
if(document.getElementById("type").value == "false"){
alert("로그인 실패");
}
function login(){
var form = document.loginForm;
if(!form.id.value){
alert("아이디를 입력해주세요.");
return
}
if(!form.password.value){
alert("비밀번호를 입력해주세요.");
return
}
form.submit();
}
</script>
</html>
- login_ok.jsp (세션 값 저장하기)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String id = request.getParameter("id");
String pw = request.getParameter("password");
if(id.equals("test") && pw.equals("test")){
session.setAttribute("id", id);
response.sendRedirect("login_success.jsp");
}else{
response.sendRedirect("login.jsp?type=false");
}
%>
- login_success.jsp (세션 값 가져오기)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인 성공</title>
</head>
<body>
<h1>
<%=session.getAttribute("id")%>님 환영합니다!
</h1>
<input type="button" onclick="goLogout()" value="로그아웃">
</body>
<script>
function goLogout(){
location.href="logout.jsp";
}
</script>
</html>
- logout.jsp (세션 삭제하기)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
session.invalidate(); //세션 전체 삭제
//session.removeAttribute("id"); //특정 세션 값 삭제
%>
<script>
location.href = "login.jsp";
</script>
- 실행결과
'웹 > JSP' 카테고리의 다른 글
JSP EL과 JSTL 이란? (0) | 2023.08.06 |
---|---|
JSP 쿠키(Cookie) 생성, 수정, 삭제 방법 (0) | 2023.06.27 |
JSP Ajax GET 방식과 POST 방식 (0) | 2023.06.24 |
JSP Ajax(Asynchronus Javascript and XML)란? (0) | 2023.06.08 |
JSP GET 방식과 POST 방식 차이 (0) | 2023.06.07 |