자바

쿠키, 세션

chantleman 2024. 9. 4. 10:06

 

쿠키

 

웹 서버와 브라우저는 애플리케이션을 사용하는 동안 필요한 값을 쿠키를 통해 공유하며 상태를 유지함

 

1. 구성요소

- 이름(key)

- 값(value)

- 유효시간(초)

- 도메인: 쿠키의 도메인이 쿠키를 생성한 서버의 도메인을 벗어나면 브라우저는 쿠키를 저장하지 않는다.

- 경로: 쿠키를 공유할 기준 경로를 저장한다.

 

2. 동작방식

- 쿠키생성단계: 생성한 쿠키를 응답 데이터의 헤더에 저장하여 브라우저에 전송

- 쿠키저장단계: 브라우저는 응답데이터에 포함된 쿠키를 쿠키저장소에 저장

- 쿠키전송단계: 브라우저는 저장한 쿠키를 요청이 있을 때마다 웹서버에 전송

 


세션

 

- 세션을 통해서 사용자별로 구분하여 정보를 관리할 수 있다. (세션 ID 이용)

- 쿠키를 사용할 때보다 보안이 향상된다. (서버 사이드에 저장되기 때문)

 

 

1. 세션 객체를 가져오는 방법

 

HttpSession session = req.getSession(boolean 값)

  → boolean: true        =>   세션 객체가 존재하지 않으면 새로 생성함

                      false      =>   세션 객체가 존재하지 않으면 null  

 

 

2. 세션 객체 삭제 처리 방법

  •  invalidate() 메소드 사용
  •  setMaxInactiveInterval(int interval) 메소드 호출 → 일정 시간동안 요청이 없으면 세션 객체 삭제 
  •  web.xml <session-config> 이용하여 설정하기 (분단위)

 예 ) 학교 수강신청할 때 30분동안만 로그인 지속되게 함

        

로그인 정보를 쿠키에 저장하면 모두가 볼 수 있기때문에 세션에 저장해야합니다.

 

 

 

 

  쿠키 세션
저장위치 클라이언트(접속자pc) 웹서버
소멸시기 쿠키 저장시 만료기간 설정 브라우저 종료시 만료기간에 상관없이 삭제(만료기간 지정 가능)
저장타입 파일 객체
저장정보 지워져도 되고, 조작되거나 가로채이더라도 큰 지장이없는 수준의 정보들 사용자나 다른 누군가에게 노출되면 안되는 중요한 정보들
속도 쿠키>세션
보안 쿠키< 세션

 

 

 


쿠키 예제

 

 

setCookieExam() 메소드 실행했을 때 

<hide/>
	private void setCookieExam(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		//쿠키 생성하기
		Cookie userId = new Cookie("userId", req.getParameter("userId"));
		Cookie name = new Cookie("name",req.getParameter("name"));
		
		//쿠키 소멸 시간 저장하지 않으면 브라우저가 종료시 쿠키를 삭제함
		userId.setMaxAge(60*60*24);
		
		//javaScript를 이용한 직접 접근(조작) 방지
		userId.setHttpOnly(true);
		
		resp.addCookie(userId);
		resp.addCookie(name);
		
		PrintWriter out= resp.getWriter();
		String title="쿠키 설정 예제";
		out.print("<html>");
		out.print("<head>");
		out.print("<title>"+title+"</title>");
		out.print("</head>");
		out.print("<body>");
		out.print(req.getParameter("userId"));
		out.print(req.getParameter("name"));
		out.print("</body>");
		out.print("</html>");
		
	}

 

 

?userId= {userid} & name={name} 쿼리 직접 입력하면 쿠키에 저장된 것을 확인할 수 있습니다.

(F12 - Application - Cookies에서)

 

 

 

 


 

readCookieExam() 메소드 실행했을 때 

<hide/>
	private void readCookieExam(HttpServletRequest req, HttpServletResponse resp)throws IOException {
		Cookie[] cookies = req.getCookies();
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html");
		
		PrintWriter out= resp.getWriter();
		
		String title="쿠키 설정 읽기 예제";
		out.print("<html>");
		out.print("<head>");
		out.print("<title>"+title+"</title>");
		out.print("</head>");
		out.print("<body>");
		for(Cookie cookie:cookies) {
			out.print("<p>name: "+cookie.getName()+"</p> <br>");
			out.print("<p>value: "+cookie.getValue()+"</p> <br>");
		}
		
		out.print("</body>");
		out.print("</html>");
	}

 

 

아까 저장했던 쿠키 정보를 불러온 것을 확인할 수 있습니다.

 

 

 

 


 

 

deleteCookieExam() 메소드 실행했을 때

<hide/>
	private void deleteCookieExam(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		Cookie[] cookies = req.getCookies();
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html");
		
		PrintWriter out = resp.getWriter();
		String title = "쿠키정보 삭제 예제";
		
		out.print("<html>");
		out.print("<head>");
		out.print("<title>"+title+"</title>");
		out.print("</head>");
		out.print("<body>");
		
		if(cookies!=null) {
			for(Cookie cookie:cookies)
			{
				cookie.setMaxAge(0);
				resp.addCookie(cookie);
				out.print("<p>삭제 요청한 쿠키: "+cookie.getName()+"</p><br>");
				out.print("<p>삭제 요청한 쿠키: "+cookie.getValue()+"</p><br>");
			}
		}
		else {
			out.print("<h2>쿠키 정보가 없습니다.</h2>");
		}
		
		out.print("</body>");
		out.print("</html>");
	}

 

 

쿠키 정보가 삭제된 것을 확인할 수 있습니다.

 

 

 

 


 

<전체코드 >

<hide/>
	public class T05ServletCookieTest extends HttpServlet{
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.setCharacterEncoding("UTF-8");
            setCookieExam(req,resp);
    //		readCookieExam(req,resp);
    //		deleteCookieExam(req,resp);
        }

        private void deleteCookieExam(HttpServletRequest req, HttpServletResponse resp) throws IOException{
            Cookie[] cookies = req.getCookies();
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html");

            PrintWriter out = resp.getWriter();
            String title = "쿠키정보 삭제 예제";

            out.print("<html>");
            out.print("<head>");
            out.print("<title>"+title+"</title>");
            out.print("</head>");
            out.print("<body>");

            if(cookies!=null) {
                for(Cookie cookie:cookies){
                    cookie.setMaxAge(0);
                    resp.addCookie(cookie);
                    out.print("<p>삭제 요청한 쿠키: "+cookie.getName()+"</p><br>");
                    out.print("<p>삭제 요청한 쿠키: "+cookie.getValue()+"</p><br>");
                }
            }
            else {
                out.print("<h2>쿠키 정보가 없습니다.</h2>");
            }

            out.print("</body>");
            out.print("</html>");
        }

        private void readCookieExam(HttpServletRequest req, HttpServletResponse resp)throws IOException {
            Cookie[] cookies = req.getCookies();
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html");

            PrintWriter out= resp.getWriter();

            String title="쿠키 설정 읽기 예제";
            out.print("<html>");
            out.print("<head>");
            out.print("<title>"+title+"</title>");
            out.print("</head>");
            out.print("<body>");
            for(Cookie cookie:cookies) {
                out.print("<p>name: "+cookie.getName()+"</p> <br>");
                out.print("<p>value: "+cookie.getValue()+"</p> <br>");
            }

            out.print("</body>");
            out.print("</html>");
        }

        private void setCookieExam(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            //쿠키 생성하기
            Cookie userId = new Cookie("userId", req.getParameter("userId"));
            Cookie name = new Cookie("name",req.getParameter("name"));

            //쿠키 소멸 시간 저장하지 않으면 브라우저가 종료시 쿠키를 삭제함
            userId.setMaxAge(60*60*24);

            //javaScript를 이용한 직접 접근(조작) 방지
            userId.setHttpOnly(true);

            resp.addCookie(userId);
            resp.addCookie(name);

            PrintWriter out= resp.getWriter();
            String title="쿠키 설정 예제";
            out.print("<html>");
            out.print("<head>");
            out.print("<title>"+title+"</title>");
            out.print("</head>");
            out.print("<body>");
            out.print(req.getParameter("userId"));
            out.print(req.getParameter("name"));
            out.print("</body>");
            out.print("</html>");
        }
    }

 

 


세션 예제

 

<hide/>
	@WebServlet("/T06")
    public class T06ServletSessionTest extends HttpServlet {

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            HttpSession session = req.getSession(true);

            //생성 시간 가져오기
            Date date = new Date(session.getCreationTime());

            //마지막 접근시간 가져오기
            Date lastAccessTime = new Date(session.getLastAccessedTime());

            String title = "";
            int visitCnt = 0;
            String userId="sem";

            session.setMaxInactiveInterval(30); //30분동안 세션 유지

            if(session.isNew()) {
                title = "처음 방문을 환영합니다.";
                session.setAttribute("userId", userId);
            }
            else {
                visitCnt = (int) session.getAttribute("visitCnt");
                visitCnt++;
                userId = (String) session.getAttribute("userId");
            }
            session.setAttribute("visitCnt", visitCnt);

            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html");

            PrintWriter out = resp.getWriter();

            out.println("<html>");
            out.println("<title>"+title+"</title>");
            out.println("<body>");
            out.println("<p> 세션ID: "+session.getId()+"</p><br>");
            out.println("<p> 생성시간: "+date+"</p><br>");
            out.println("<p> 마지막 접근시간: "+lastAccessTime+"</p><br>");
            out.println("<p> 사용자 id: "+userId+"</p><br>");
            out.println("<p> 방문 횟수: "+visitCnt+"</p><br>");
            out.println("</body>");
            out.println("</html>");
        }
    }

 

 

 

브라우저별로 세션 ID가 다른 것 확인

 

 

'자바' 카테고리의 다른 글

getAttribute(), getParameter(), VO  (1) 2024.09.08
servlet filter  (0) 2024.09.04
웹모듈 배포  (0) 2024.09.02
servlet  (0) 2024.09.02
resultType과 resultMap 차이  (0) 2024.09.01