Untitled_Blue

[JSP] 쿠키와 세션 본문

JSP&Servlet

[JSP] 쿠키와 세션

Untitled_Blue 2024. 3. 16. 21:47
반응형

안녕하세요. 이번 글은 쿠키와 세션에 대한 설명입니다.

- 세션이란?

  • 클라이언트의 정보를 서버에 저장하지 않고 클라이언트의 PC에 저장하는 방식

상단의 이미지처럼 쿠키는 사용자의 접속정보를 서버에 저장하지 않고 브라우저에 저장하는 방식을 사용한다. 쿠키를 서버에 전송할 때 요청 정보랑 쿠키를 기반으로 요청에 대한 응답을 진행하고 쿠키를 활용하여 기존에 접속한 적이 있는지와 동일한 정보인지를 확인한다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cookie LOGIN</title>
</head>
<body>
<form action="<%=request.getContextPath() + "/Login.do"%>" method="post">
	ID : <input type="text" name="id"> <br>
	PW : <input type="password" name="pwd"> <br>
	<input type="checkbox" name="InfoSave"> 로그인 정보 저장 <br>
	
	<input type="submit"> <br>
</form>
</body>
</html>

상단의 코드는 로그인하는 화면이다. form action에서 볼 수 있듯이 로그인 화면에서 입력한 정보를 모두 Controller로 전송할 것이다. 전송할 정보 안에는 아이디 정보 여부를 물어보는 체크박스도 포함되어있다.

package Testing;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/Login.do")
public class TestController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public TestController() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		
		String id = (String) request.getParameter("id");
		String pwd = (String) request.getParameter("pwd");
		
		String chkBox = request.getParameter("InfoSave");
		
		Cookie ck = new Cookie(id, "id");
		
		if (chkBox != null) {
			ck.setMaxAge(60*60*24*365);
			response.addCookie(ck);
		}
		else {
			ck.setMaxAge(0);
			response.addCookie(ck);
		} 
		
		if (id.equals("test") && pwd.equals("1234")) {
			request.setAttribute("id", id);
			request.setAttribute("pwd", pwd);
			
			String vUrl = "/CookieTest.jsp";
			RequestDispatcher rd = request.getRequestDispatcher(vUrl);
			
			rd.forward(request, response);
		}
		else {
			String vUrl = "/CookieLogin.jsp";
			RequestDispatcher rd = request.getRequestDispatcher(vUrl);
			
			rd.forward(request, response);
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

다음은 로그인한 정보를 기반으로 쿠키를 생성하고 처리하는 컨트롤러 파일이다. 상단처럼 request.getParameter()를 통해 프론트엔트에서 입력한 정보를 가져오고 이를 기반으로 생성해둔 쿠키를 바탕으로 쿠키의 수명을 설정하거나 삭제하는 과정을 거치고 클라이언트에게 쿠키를 전달한다.

<%@ 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>RESULT</h1>

ID : <%=request.getAttribute("id") %><br>
PWD : <%=request.getAttribute("pwd") %><br>
</body>
</html>

다음은 입력한 정보를 보여주는 화면이다. 이때 백엔드에서 설정해둔 request.setAttribute()를 활용해서 정보를 가져온다.

코드 설명
Cookie cookie = new Cookie("CookieName", "CookieValue") Cookie 클래스를 기반으로 객체 생성
cookie.setMaxAge(int expiry) 쿠키의 수명 설정
cookie.setValue("CookieValue") , cookie.getValue() 쿠키의 값을 설정하고 읽어옴
response.addCookie(cookie) 쿠키를 클라이언트에게 전달
response.getCookies() 쿠키를 읽어옴

- 세션 (Session)

  • 쿠키와 다르게 요청 정보를 웹 브라우저에 저장하는 것이 아닌 서버에 저장하는 방식
  • 웹 브라우저 한 개당 한 개의 세션이 부여되며 브라우저 종료 또는 세션 유효시간 만료 시 소멸
  • 주로 로그인한 상태를 유지하기 위해 사용되고 있다.
<div id="wrap">
  <%@include file="./header.jsp" %>

  <center>
    <div class="login">
      <form action="<%=request.getContextPath() + "/PJT/LoginProc.jsp"%>" method="post">
      <input type="hidden" name="category" value="MemLogin">
      
        <table>
          <tr>
            <th colspan="3">LOGIN</th>
          </tr>
          <tr>
            <td>ID</td>
            <td><input type="text" name="id" class="ins"></td>
            <td rowspan="2"><input type="submit" value="LOGIN" class="btn"></td>
          </tr>
          <tr>
            <td>PW</td>
            <td><input type="password" name="pwd" class="ins"></td>
          </tr>
          <tr>
            <td colspan="3">
              <button><a href="<%=request.getContextPath() + "/MemberController.do"%>?category=MemJoin">회원가입</a></button>
              <button><a href="<%=request.getContextPath() + "/MemberController.do"%>?category=Find_IDPW">ID/PW 찾기</a></button>
            </td>
          </tr>
        </table>
      </form>
    </div>
  </center>
  <%-- <%@include file="./footer.jsp" %> --%>
  <jsp:include page="./footer.jsp"></jsp:include>
</div>

상단의 코드는 로그인하는 화면을 구현하는 JSP이며 form 태그를 통해 로그인을 검증하는 화면으로 정보가 전송된다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <jsp:useBean id = "dao" class="Member.MemberDAO"/>
    <jsp:useBean id = "dto" class="Member.MemberDTO"/>
    <jsp:setProperty property="*" name="dto"/>
<%

String mid = request.getParameter("id");	//form에 있는값 (id아닌 name값),
String pwd = request.getParameter("pwd");   //id값은 server로 넘어가지않음 name에 해당하는 value값이 넘어갑

int b = dao.memLog(dto.getId(), dto.getPwd());


if(b != 0){
	//로그인 성공
	session.setAttribute("id", dto.getId());
	response.sendRedirect("../PJT/index.jsp");
	
} else {%>
<script>
	alert('로그인에 실패하였습니다');
	
	location.href='<%=request.getContextPath() + "/PJT/Login.jsp"%>';
</script>
<% } %>

로그인 폼에서 작성하고 전송했던 정보가 상단의 코드에서 받아서 처리한다. 이때 빈즈에 해당되는 DTO와 실질적인 로직을 처리하고 검증하는 DAO를 활용한다.

package Member;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import common.DbClose;
import common.DbSet;

public class MemberDAO {
	String sql;
	public PreparedStatement pstmt;
	public Connection conn;

	MemberDTO dto = new MemberDTO();
	
	public int memLog(String id, String pwd) {
		int su = 0;
		sql = "select * from PJT_MEMBER where MEM_ID = ? and MEM_PW = ?";

		try {
			conn = DbSet.getConnection();

			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, id);
			pstmt.setString(2, pwd);

			su = pstmt.executeUpdate();

		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DbClose.close(conn, pstmt);
		}
		
		return su;
	}
}

상단의 코드는 DAO인데 JDBC를 활용해서 데이터베이스에 있는 데이터를 기반으로 로그인 성공 또는 실패를 결정한다.

더보기

package common;

import java.sql.Connection;
import java.sql.DriverManager;

public class DbSet {
public static Connection getConnection() throws Exception {
String url = "jdbc:oracle:thin:@localhost:1521:orcl";

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(url, "[ID]", "[PWD]");

return conn;
    }
}

상단의 코드는 JDBC를 활용해서 데이터베이스와 연결하는 역할을 담당하는 코드이다.

더보기

package common;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DbClose {
public static void close(Connection conn, Statement stmt) {
try {
    stmt.close();
   conn.close();
} catch (SQLException e) {
   e.printStackTrace();
  }
}

public static void close(Connection conn, Statement stmt, ResultSet rs) {
try {
   conn.close();
   stmt.close();
   rs.close();
} catch (SQLException e) {
   e.printStackTrace();
  }
}
}

상단의 코드는 데이터베이스와의 연결을 종료하는 역할을 담당한다.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
 <%
 	request.setCharacterEncoding("UTF-8");
 	String printing = "";
 	String printing02 = "";
 	String url_id = "";
 	String url_id2 = "";
 	try {
 		if (session.getAttribute("id").equals("")) {
 	 		printing = "로그인";
 	 		printing02 = "회원가입";
 	 		url_id = request.getContextPath() + "/PJT/Login.jsp";
 	 		url_id2 = request.getContextPath() + "/MemberController.do?category=MemJoin";
 	 	}
 	 	else {
 	 		printing = "로그아웃";
 	 		printing02 = "마이페이지";
 	 		url_id = request.getContextPath() + "/PJT/Logout.jsp";
 	 		url_id2 = request.getContextPath() + "/MemberController.do?category=MyPage";
 	 	}
 	} catch(NullPointerException e) {
 		printing = "로그인";
	 	printing02 = "회원가입";
	 	url_id = request.getContextPath() + "/PJT/Login.jsp";
	 	url_id2 = request.getContextPath() + "/MemberController.do?category=MemJoin";
 	} 
 	
 	session.setAttribute("vId", session.getAttribute("id"));
 %>
 
 <div class="Star_Function" align="right">
      <a href="#" class="link_cust">접속자 : <%=session.getAttribute("id") %></a>
      <a href="<%=url_id%>" class="link_cust" target="_top" id="ID_Link"><%=printing %></a>
      <a href="<%=url_id2%>" class="link_cust" id="ID_Link2"><%=printing02 %></a>
      <a href="<%=request.getContextPath() + "/ProductController.do"%>?category=Cart" class="link_cust">장바구니</a>
</div>

다음과 같이 로그인을 검증하는 과정을 거치게 되면 상단의 코드로 이동하게 될 것이다. 로그인에 성공하게 되면 session.setAttribute("Key", Value)을 통해 세션이 설정되며 session.getAttribute("Key")을 통해 세션의 값을 읽어와서 로그인 정보를 유지할 수 있게 된다. 이를 활용하면 로그인을 유지하고 있는 세션을 바탕으로 회원전용 서비스를 시작으로 회원정보 수정, 탈퇴, 로그아웃같은 기능을 구현할 수 있다.

추가로 session.setMaxInactiveInterval(minute)을 사용하면 세션의 유효시간을 설정할 수 있다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% session.invalidate(); %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<script type="text/javascript">
		alert('로그아웃 되었습니다.');
		location.href="<%=request.getContextPath() + "/PJT/index.jsp"%>";
	</script>
</body>
</html>

다음과 같이 session.invalidate()를 사용하면 세션을 무효화함으로써 로그아웃 기능을 구현할 수 있다.

해당 코드를 실행하면 상단의 이미지처럼 로그인한 데이터를 바탕으로 세션의 값을 통해 로그인/로그아웃 기능뿐만 아니라 회원가입/마이페이지 기능을 구현하고 실행할 수 있다.

반응형

'JSP&Servlet' 카테고리의 다른 글

[JSP]JSTL/EL 언어  (0) 2024.06.28
[JSP] cos.jar를 활용한 파일 업로드  (0) 2024.06.12
[JSP] JavaBeans (자바빈즈)  (1) 2023.10.09
[JSP] 액션태그  (0) 2023.10.08
[JSP] 내장객체  (1) 2023.10.07