본문 바로가기

개인프로젝트

[내가 만든 프로젝트 코드 분석 | JSP게시판 만들기] 7.접속한 회원 세션 관리하기

회원접속 상태를 관리하기 위해 현재 접속한 회원에게 고유의 세션ID를 할당합니다.

loginAction.jsp와 joinAction.jsp에 로그인에 성공한 회원에게 세션ID를 부여해주도록 하겠습니다.

String userID = null;
	if (session.getAttribute("userID") != null){ // userID에 세션이 존재하는 경우
		userID = (String) session.getAttribute("userID"); // 세션ID 부여
	}
	if (userID != null) {
		PrintWriter script = response.getWriter();
	 	script.println("<script>");
	 	script.println("alert('이미 로그인이 되어있습니다.')");
	 	script.println("location.href = 'main.jsp'");
	 	script.println("</script>");
		}
    
UserDAO userDAO = new UserDAO();
	int result = userDAO.join(user);
	if(result == -1) {
		PrintWriter script = response.getWriter();
		script.println("<script>");
		script.println("alert('이미 존재하는 아이디입니다.')");
		script.println("history.back()");
		script.println("</script>");
	}
	else {
		session.setAttribute("userID", user.getUserID()); // 세션에 userID속성 설정
		PrintWriter script = response.getWriter();
		script.println("<script>");
		script.println("location.href = 'main.jsp'");
		script.println("</script>");
	}
<body>
	<%
 		String userID = null;
		if (session.getAttribute("userID") != null){ // userID에 세션이 존재하는 경우
			userID = (String) session.getAttribute("userID");	// 세션ID 부여
		}
		if (userID != null) { // 로그인 된 사람은 재로그인 접근 불가
			PrintWriter script = response.getWriter();
 			script.println("<script>");
 			script.println("alert('이미 로그인이 되어있습니다.')");
 			script.println("location.href = 'main.jsp'");
 			script.println("</script>");
		}	 	
		if(user.getUserID() == null || user.getUserPassword() == null || user.getUserName() == null || user.getUserGender() == null || user.getUserEmail() == null){
			PrintWriter script = response.getWriter(); // 사용자의 미입력 경우의 수 체크 
	 		script.println("<script>");
	 		script.println("alert('입력이 안 된 사항이 있습니다.')"); // 사용자에게 반환 메세지
	 		script.println("history.back()"); // 뒤로가기
	 		script.println("</script>");
	                                	.
	                                  .
	                                  .
		 	else {
		 		session.setAttribute("userID", user.getUserID()); // 세션에 userID속성 설정
		 		PrintWriter script = response.getWriter();
		 		script.println("<script>");
		 		script.println("location.href = 'main.jsp'"); // 회원가입 성공시 메인으로 접근
		 		script.println("</script>");
		 	}
	 	}		
	%>
</body>

할당된 세션을 해지는 로그아웃페이지에서 수행하였습니다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import = "user.UserDAO" %>
<%@ page import = "java.io.PrintWriter" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP 게시판 웹 사이트</title>
</head>
<body>
	<%
	 	session.invalidate(); // 부여된 세션ID의 모든데이터 삭제
	%>
	<script>
		location.href = 'main.jsp';
	</script>
</body>
</html>