Purple Bobblehead Bunny

Backend/JSP SERVLET

[JSP] 쿠키, Cookie

준영어린이 2022. 6. 30. 17:42

 

쿠키(Cookie)

  • 클라이언트와 웹 서버 간의 상태를 지속적으로 유지하는 방법
  • 쿠키는 상태 정보를 클라이언트에 저장
    • ex) 어떤 웹 사이트를 처음 방문한 사용자가 로그인 인증을 하면 아이디와 비밀번호를 기록한 쿠키가 만들어지고 그 다음부터 사용자가 동일한 사이트에 접속하면 별도의 절차 없이 쉽게 접속이 가능
  • 클라이언트의 일정 폴더에 정보를 저장하기 때문에 웹 서버의 부하를 줄일 수 있다.
  • 웹 브라우저가 접속했던 웹 사이트에 관한 정보와 개인 정보가 기록이 되기 때문에 보안에 취약하다.

 

 

 

쿠키의 동작 과정

  • 생성 단계 
    • 쿠키는 주로 웹 서버 측에서 생성
    • 생성된 쿠키는 응답 데이터에 함께 저장되어 웹 브라우저에 전송
  • 저장 단계 
    • 웹 브라우저는 응답 데이터에 포함된 쿠키를 쿠키 저장소에 보관
    • 쿠키는 종류에 따라 메모리나 파일로 저장
  • 전송 단계 
    • 웹 브라우저는 한 번 저장된 쿠키를 요청이 있을 때마다 웹 서버에 전송
      • 웹 서버는 웹 브라우저가 전송한 쿠키를 사용하여 필요한 작업을 수행

 

쿠키 생성

  • Coocke() 메서드를 사용하여 쿠키 생성
  • response 내장 객체의 addCookie() 메서드로 쿠키 설정
Cookie Cookie(String name, String value)
  • 매개 변수
    • name - 쿠키를 식별하기 위한 이름
    • value - 쿠키 값
  • Cookie() 메서드 사용 예
Cookie cookie = new Cookie("memberId", "admin");
response.addCookie(cookie);

 

 

// cookie01.jsp

<%@ page contentType="text/html; charset=utf-8 %>
<html>
<head>
<title>Cookie</tktle>
</head>
<body>
	<form action="cookie01_process.jsp" method="POST">
    	<p> ID : <input type="text" name="id">
        <p> PW : <input type="text" name="passwd">
        <p><input type="submmit" value="전송">
    </form>
</body>
</html>
// cookie_process.jsp

<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Cookie</title>
</head>
<body>
	<%
    	String userId = request.getParameter("id");
        String userPwd = request.getParameter(""passwd");
        
        if(userId.equals("admin") && userPwd.equals("1234")){
        Cookie cookieId = new Cookie("userID", userid);
        Cookie cookiePwd = new Cookie("userPW", userPwd);
        response.addCookie(cookieId);
        response.addCookie(cookiePwd);
        	out.pritnln("쿠키 생성 성공");
        }else{
       		out.println("쿠키 생성 실패");
        }
     %>
</body>
</html>

 

 

쿠키 정보 - 쿠키 객체 얻기

 

  • request 내장 객체의 getCookies() 메서드
    • 클라이언트에 저장된 모든 쿠키 객체를 가져올 때 사용
  • 쿠키 객체가 여러 개일 때는 배열 형태로 가져옴
    • Cookie[] request.getCookies()
  • getCookies() 메서드 사용 예
    • Cookie[] cookies = request.getCookies();

 

쿠키 정보 - 쿠키 객체의 정보 얻기

 

  • 쿠키 객체에 저장된 쿠키 이름과 값을 가져오기 위해 getName(), getValue() 메서드 사용
    • String getName()             String getValue()
  • getName(), getValue() 메서드 사용 예
Coockie[] cookies = request.getCookies();

for(int i=0; i<cookies.length; i++) {
	out.println(cookies[i].getName()+" : "+ cookies[i].getValue() + "<br>"); 
    }

 

쿠기 객체의 저장 된  모든 쿠키 값 출력

 

<%@ page contentType="text/html; charset=utf-8" %>
<html>
<head>
<title>Cookie</title>
</head>
<body>
	<%
    	Cookie[] cookies = request.getCookies();
        out.println("현재 설정 된 쿠키의 갯수 > " + cookies.length + "<br>");
        out.println("==================<br>");
        for(int i =0; i<cookies.length; i++) {
		out.println("설정된 쿠키의 속성 이름 [ " + i + " : ] : "
        					+ cookies[i].getName() + "<br>");
		out.println("설정된 쿠키의 속성 값 [ " + i +  " : ] : "
        					+ cookies[i].getValue() + "<br>");
  	 %>
</body>
</html>

 

 

쿠키 삭제

 

  • 쿠키의 유효 기간을 결정하는 setMaxAge() 메서드에 유효 기간으로 0으로 설정하여 삭제
  • setMaxAge() 메서드의 형식
    • void setMaxAge(int age)
  • setMaxAge() 메서드의 사용 예
Cookie cookie = new Cookie("memberId", "admin");
cookie.setMaxAge(0);
response.addCookie(cookie);

 

<%@ page contentType="text/html; charset=utf-8" %>
<html>
<head>
<title>Cookie</title>
</head>
<body>
	<%
    	Cookie[] cookies = request.getCookies();
        for (int i=0; i<cookies.length; i++) {
        	cookies[i].setMaxAge(0);
            response.addCookie(cookies[i]);
        }
        response.sendRedirect("cookies02.jsp");

 

 

'Backend > JSP SERVLET' 카테고리의 다른 글

[JSP] JDBC  (0) 2022.07.02
[Servlet]MVC Pattern  (0) 2022.07.01
[JSP] request.getParameter(), getAttribute()  (0) 2022.06.28
[JSP] 세션(Session)  (0) 2022.06.28
[JSP] 내장 객체(implicit object)  (0) 2022.06.28