본문 바로가기
Spring/JSP

[JSP] 세션(Session)을 사용한 로그인과 로그아웃

by JJH0100 2022. 11. 21.
728x90
반응형

2022.11.21 - [JSP] - [JSP] 세션(Session)

 

[JSP] 세션(Session)

Ex01. setSession.jsp 세션 설정 getSession.jsp 세션 값 가져오기 2022.11.21 - [JAVA/개념정리] - [Java] 래퍼 클래스(Wrapper Class) [Java] 래퍼 클래스(Wrapper Class) 자바의 자료형은 크게 기본 타입(primitive type)과 참조

jjh93.com

 

 

loginForm.jsp

<%@ 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>
<h2>회원 로그인 폼</h2>
<form method="post" action="testLogin.jsp">
	아이디 : <input type="text" name="id"><br>
	암 호 : <input type="password" name="pwd"><br>
	<input type="submit" value="로그인">
</form>
</body>
</html>

 

testLogin.jsp

<%@ 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 = "root";
	String pw = "1234";
	String name = "홍길동";
	
	if(id.equals(request.getParameter("id")) && 
			pw.equals(request.getParameter("pwd"))){
		session.setAttribute("loginUser", name);
		response.sendRedirect("main.jsp");
	} else {
		response.sendRedirect("loginForm.jsp");
	}
%>
</body>
</html>

아이디와 패스워드를 검증하여 root, 1234일 경우 session을 발급받아 main.jsp로 전송.

아닐 경우 loginForm으로 돌아감

 

main.jsp

<%@ 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>
<%
	if(session.getAttribute("loginUser") == null){
		response.sendRedirect("loginForm.jsp");
	}else{
		
%>
<%=session.getAttribute("loginUser") %>님 안녕하세요!<br>
저희 홈페이지에 방문해 주셔서 감사합니다. <br>
즐거운 시간 되세요...<br>
<form action="logout.jsp" method="post">
	<input type="submit" value="로그아웃">
</form>
<%
	}
%>
</body>
</html>

session을 검증하고 들어왔더라도, session의 loginUser값이 빈값이면 다시 로그인폼으로 돌아감

 

logout.jsp

<%@ 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>
<%
	session.invalidate();
%>
<script>
 alert("로그 아웃 되었습니다.");
 location.href = "loginForm.jsp";
</script>
</body>
</html>

728x90
반응형

'Spring > JSP' 카테고리의 다른 글

[JSP] mysql-connector-j-8.0.31 설치  (0) 2022.11.22
[JSP] 자바빈즈 (Java Beans)  (0) 2022.11.22
[JSP] 세션(Session)  (0) 2022.11.21
[JSP] 쿠키(Cookie)  (0) 2022.11.21
[JPS] 쿠키(Cookie)와 세션(Session)  (0) 2022.11.21

댓글