티스토리 뷰

직전 포스팅에서 알아본 세션을 활용하여 간단한 로그인, 로그아웃 기능을 구현해보자.

로그인된 사용자의 이름 정보가 세션에 저장되고, 로그아웃을 클릭한다면, 해당 세션 자체를 삭제하는 구조이다.


●loginForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE>
<html>
<head>
<meta charset="UTF-8">
<title>로그인 화면</title>
</head>
<body>
	<form action = "testLogin.jsp" method = "post"> 
		아이디 : <input type = "text" name = "id" required = "required" />
		<br />
		비밀번호 : <input type = "password" name = "pwd" required = "required"/>
		<br />
		<input type  = "submit" value = "로그인"/> 
	</form>
</body>
</html>

●testLogin.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
	String a_id = "admin";
	String a_pwd = "1234";
	String a_name = "관리자";
	
	request.setCharacterEncoding("UTF-8");
	String id = request.getParameter("id");
	String pwd = request.getParameter("pwd");
	
	if(a_id.equals(id) && a_pwd.equals(pwd)){ //올바른 아이디, 비밀번호를 입력했을 때, 세션에 name을 저장한다.
		session.setAttribute("loginUser", a_name);
		response.sendRedirect("main.jsp");
	} else{
		response.sendRedirect("loginForm.jsp");
	}

%>

●main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%= session.getAttribute("loginUser")  %> ㅎㅇㅎㅇ
	<br/>
	<form action = "logout.jsp" method = "post"> 
		<input type = "submit" value = "로그아웃"/>
	</form>
</body>
</html>

●logout.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
	session.invalidate();   //세션 자체를 삭제
%>
 <script type = "text/javascript">
 	alert("로그아웃 되었습니다."); //alert를 닫아야 다음 코드로 넘어감
 	document.location.href = "loginForm.jsp";
 </script>

로그인 페이지
메인 페이지

잘 실행되는 것 같아 보이지만, 위와 같이 코드를 작성한다면 따로 세션을 가지고 있지 않아도, main.jsp에 직접 접속이 가능한 문제가 발생한다.

그렇기 때문에 이를 방지하기 위해 main 페이지를 조금 수정할 필요가 있다.


●main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
	if(session.getAttribute("loginUser") == null){
		response.sendRedirect("loginForm.jsp");
	} else {
%>
	<%= session.getAttribute("loginUser")  %> ㅎㅇㅎㅇ
	<br/>
	<form action = "logout.jsp" method = "post"> 
		<input type = "submit" value = "로그아웃"/>
	</form>
	<% }%>
</body>
</html>

 

 

끝!

'WEB > DynamicWeb' 카테고리의 다른 글

[JSP] Beans - property 쉽게 사용하기  (0) 2021.04.23
[JSP] JAVA Beans  (0) 2021.04.23
[JSP] 쿠키와 세션  (0) 2021.04.23
[JSP] Action Tags  (0) 2021.04.22
[JSP] JSP -> JSP 로 데이터를 전달하는 다양한 방법  (0) 2021.04.21
Comments