본문 바로가기
jsp

210318 session을 사용해서 로그인 인증하기

by 정ㅇr 2021. 3. 18.
728x90

- session 개념을 위한 예제 (참고 : jsp 책 270쪽 - 세션 개념) 

a.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.setAttribute("name", "goodee"); // 세션 안에 변수를 만들 때 쓰는 폼 (String name = "goodee")
%>
	<h1>a.jsp</h1>
	<a href="./b.jsp">b</a>
</body>
</html>

b.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>
	<h1>b.jsp</h1>
	<!-- a.jsp의 name변수 값은 읽을 수가 없다. -->
	<!-- a.jsp에서 session에 만든 변수는 읽을 수 있다. -->
	<!-- session 하나의 클라이언트(브라우저)에서 호출한 jsp페이지가
		 공유할 수 있는 공간(변수를 만드는 공간) 
	-->
	<%=session.getAttribute("name")%>
</body>
</html>

 

- session을 이용해서 로그인 창, 로그인 성공, 로그아웃 기능 구현하기

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>
	<h1>loginForm</h1>
	<form action="./loginAction.jsp" method="post">
		<div>id : <input type="text" name="id"></div>
		<div>pw : <input type="password" name="pw"></div>
		<button type="submit">로그인</button>
	</form>
</body>
</html>

loginAction.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
	// loginAction
	String id = request.getParameter("id");
	String pw = request.getParameter("pw");
	
	// 원래는 DB에서 id, pw 값을 받아와야 하는데, 여기서 임의로 지정
	String sysId = "admin";
	String sysPw = "1234";
	
	if(id.equals(sysId) && pw.equals(sysPw)) {
		System.out.println("로그인 성공!");
		session.setAttribute("sessionId", id); // 세션에 로그인을 위해 입력한 id를 저장함
	} else {
		System.out.println("로그인 실패 ㅠㅠ");
	}
%>

auth.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("sessionId") == null) { // 세션에 한번도 로그인 흔적이 없는 경우
			response.sendRedirect("./loginForm.jsp");
		} else {
	%>
			<%=session.getAttribute("sessionId")%>님 반갑습니다.
			<a href="./logoutAction.jsp">로그아웃</a>
	<%
		}
	%>
</body>
</html>

logoutAction.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(); // 만들어진 세션을 갱신하라는 코드 -> 로그인 한 흔적이 지워지게 됨
	%>
</body>
</html>
반응형

'jsp' 카테고리의 다른 글

210322 배운 내용  (0) 2021.03.22
210319 쇼핑몰 만들기 (로그인 창 구현)  (0) 2021.03.19
210316 글목록(boardList)  (0) 2021.03.16

댓글