[JSP] Cookie(쿠키)

Junseo Kim·2020년 1월 12일
1

[JSP]JSP기초

목록 보기
11/19

Cookie란?

프로그램에서 흔적을 남기는 것. 클라이언트와 서버가 연결을 시도한 흔적을 남겼다가, 후에 또 연결을 시도할 시 과거의 접속을 이어나가기 위해 흔적을 사용하는 방법.

우리가 사용하는 http 프로토콜은 클라이언트가 서버에 요청하고 서버가 클라이언트로 응답을 하고 나면, 연결이 해제된다.(계속 연결하고 있으면 서버 부하가 너무 크기때문)

따라서 기존 정보를 유지하고 있을 수가 없다. 그래서 사용하는 것이 Cookie이다. 연결은 한 번의 요청과 응답 싸이클이 돌면 끊어지지만 cookie를 사용하여, 기존 연결 정보를 저장해놨다가, 보여주는 것이다.(서버가 아닌 클라이언트 쪽에 저장)

보안에 취약하므로, 중요한 정보는 저장하지 않는다.

로그인 할 때 정보저장을 cookie를 사용해서 해보려고한다.

로그인 form을 만든다. submit시, loginCheck라는 servlet으로 mapping된다.

request객체의 getParameter 메서드를 이용하여 데이터가 제대로 넘어옴을 확인할 수 있다.

이 정보를 쿠키에 저장해보겠다.

cookie는 사용자(브라우저)쪽에 존재하는 정보이기 때문에 request 객체에 들어가있다.

cookie는 다양한 정보가 들어갈 수 있으므로, 배열로 받아와야한다.

getCookies 메서드로 가져온 쿠키들을 for문으로 살펴본 후, cookie 중에 "memberId"라는 이름의 cookie가 있으면, 그 정보를 사용하고, cookie 배열을 모두 살펴봐도 "memberId" 라는 cookie 정보가 없으면, 새로 cookie를 생성한다.

기존 정보(cookie 내에 이미 정보가 존재하는 경우)나 새로 생성된 정보를 쿠키에 추가해주고, 쿠키의 유효기간을 설정해준 후, loginOk.jsp 페이지로 응답해준다.

loginOk.jsp 페이지에서는 getCookies 메소드로 저장된 쿠키를 모두 불러와서 출력해준다.

form에 입력한 정보가 cookie에 들어가 있음을 볼 수 있다.

*맨 처음 login.jsp 페이지에서 해줘야하는 일이 한 가지 더있다. cookie값이 있는지 확인하여, 있으면 login form을 띄워주는 것이 아니라 자동으로 로그인이 되어있게 해줘야한다.

위의 코드 삽입 후 실행 시, login form이 발생하지 않고 바로 loginOk.jsp로 넘어가는 것을 볼 수 있다.

전체 코드

// login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <%
        // 저장된 쿠키를 모두 가져온다.
        Cookie[] cookies = request.getCookies();

        // 쿠키가 비어있지 않으면
        if(cookies != null){
            //모든 쿠키를 살펴봐서
            for(Cookie c: cookies){
                //"memberId"라는 이름의 쿠키가 있으면
                if(c.getName().equals("memberId")){
                    // 로그인 완료 화면으로 응답해준다. 
                    response.sendRedirect("loginOk.jsp");
                }
            }
        }
    %>

    <form action="loginCheck" method="post">
        ID: <input type="text" name="userID"><br>
        Password: <input type="password" name="userPwd"><br>
        <input type="submit" value="login">
    </form>
</body>
</html>
//loginCheck.java

package com.servlet;

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;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/loginCheck")
public class loginCheck extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();

        String userId = request.getParameter("userID");
        String userPwd = request.getParameter("userPwd");

        out.println(userId);
        out.println(userPwd);

        Cookie[] cookies = request.getCookies(); // 저장된 쿠키들을 담기위한 배열
        Cookie cookie = null;

        // 저장되어 있는 쿠키 배열 검색
        for(Cookie c: cookies){
            System.out.println("cookie name: "+c.getName());
            System.out.println("cookie value: "+c.getValue());

            // 쿠키의 이름이 "memberId"와 같으면 cookie에 그 정보를 담아라.
            if(c.getName().equals("memberId")){
                cookie = c;
            }
        }

        // 쿠키 배열을 모두 살펴보아도 정보가 없는 경우 쿠키 생성
        if(cookie == null){
            System.out.println("cookie is null");
            cookie = new Cookie("memberId", userId);
        }

        // 쿠키 값을 추가해준다.
        response.addCookie(cookie);

        // 쿠키 생명 시간 설정 (1시간)
        cookie.setMaxAge(60 * 60);

        // view 페이지로 응답해줌
        response.sendRedirect("loginOk.jsp");
    }
}
//loginOk.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Login OK </title>
</head>
<body>
    <%
        Cookie[] cookies = request.getCookies();

        for(Cookie c: cookies){
            out.print("name: "+ c.getName() + "<br>");
            out.print("value: " + c.getValue()+"<br>");
            out.print("----------------------------------<br>");
        }
    %>
</body>
</html>

1개의 댓글

comment-user-thumbnail
2021년 6월 3일

정리를 너무 잘하셔서...이해가 완전 쏙쏙 됐습니다! 도움 많이 받고 가요 :)

답글 달기