JSP

JSP - session 세션 (로그인 / 로그아웃)

기련이 2020. 6. 10. 17:48

쿠키와 세션

  사용자의 사이트 접속 상태를 유지하기 위한 기술.

 

  세션
    사용자의 접속 정보를 서버에 저장.
    세션(session) 객체에 속성(Attribute)로 값을 저장
    map 형태로 데이터를 저장 - (key, value)
    세션을 새로 만드는 형식이 아니라, 접속 시 자동으로
    생성되는 세션 객체에 데이터를 저장하는 방식.
    
    세션에 데이터 저장 : setAttribute("name", "value");
    세션 데이터 불러오기 : getAttribute("name");
    세션 데이터 삭제 : removeAttribute("name");
    세션 제거(비유효화) : invalidate();
    
    세션 데이터의 변경 : setAttribute("name", "new value");

 

 

세션 로그인

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>세션 로그인</title>
</head>
<body>
<form action="lProcSession.jsp" method="post">
   <table>
      <tr>
         <td>id</td>
         <td><input type="text" name="id"></td>
      </tr>
      <tr>
         <td>password</td>
         <td><input type="password" name="pwd"></td>
      </tr>
      <tr>
         <td colspan="2" style="text-align: center;">
         <input type="submit" value="로그인">
         <input type="reset" value="취소">
         </td>
      </tr>
   </table>
</form>
</body>
</html>

id와 pwd를 입력할수 있는 창을 만들어주고

입력값을 저장

<%@ 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>
<%
String id = request.getParameter("id");
String pwd = request.getParameter("pwd");

String dbid = "user2";
String dbpwd = "1234";

if(dbid.equals(id)){
	if(dbpwd.equals(pwd)){
		session.setAttribute("id", id);
		response.sendRedirect("main2.jsp");
	}
	else{
		//비밀번호 오류.
				response.sendRedirect("loginFrm_s.jsp");
	}
}
else{
	//아이디 없음.
		response.sendRedirect("loginFrm_s.jsp");
}
%>
</body>
</html>

세션에 저장된 id와 pwd값이 일치하는지 확인 후 메인페이지로 연결

else문을 통하여 비밀번호와 아이디가 일치하지않을경우 새 로그인창 실행

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>세션 메인</title><%-- 로그인 성공시 페이지 --%>
</head>
<body>
<h2>세션 메인 페이지</h2>
<%
	String id = (String)session.getAttribute("id");//꺼내올때는 다운캐스팅을 해서 꺼냄
	if(id == null){
		response.sendRedirect("loginFrm_s.jsp");
	}
%>
<%=id %> 님 환영합니다.
<a href="logout_s.jsp">로그아웃</a>
</body>
</html>

로그아웃 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그아웃 처리</title>
</head>
<body>
<%
//Cookie user = new Cookie("id", "");
session.invalidate();//세션의 모든 속성 제거
response.sendRedirect("loginFrm_s.jsp");
%>
<!-- 로그아웃 처리 완료 -->
</body>
</html>

session.invalidate(); // 세션의 모든 속성을 제거해줌

response.sendRedirect("loginFrm_s.jsp") //로그아웃 후 로그인 페이지로 이동