IT story/JSP

[Jsp 강의] L09Cookie

jason719 2016. 10. 27. 18:32

L09Cookie

쿠키에 대해서 알아보자!

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Cookie에 대해 알아보자</title>

</head>

<body>

<h1>쿠키를 설정하고 불러오자</h1>

<hr>

<h3><a href="L01SetCookie.jsp">쿠키 설정하기</a></h3>

<h3><a href="L02GetCookie.jsp">쿠키 가져오기</a></h3>

<h3><a href="L03RemoveCookie.jsp">쿠키 삭제하기</a></h3>

<h3><a href="L04LastDate.jsp">마지막으로 접속한 날짜 알아보기</a></h3>

</body>

</html>

L01SetCookie.jsp에서 쿠키를 설정해보자!

예제 1. L01SetCookie.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>쿠키 설정</title>
</head>
<body>
    <h1>쿠키 설정</h1>
    <%
    //쿠키는 브라우저에 저장되는 객체이다. (마치 파일처럼)
    //쿠키를 생성하고 response 객체에 담으면 저장 완료.
    //세션처럼 유지되는 것이 아니라 저장에 가깝기 때문에 부라우저(response)에 넘긴다.
    Cookie c = new Cookie("id","jsplesson"); //생성과 동시에 파라미터를 저장
    Cookie c2 = new Cookie("pwd","admin1234");
    Cookie c3 = new Cookie("name","kjs");
    //만약 유효시간을 설정하지 않으면 브라우저 종료시 삭제된다.
    c.setMaxAge(365*24*60*60); //日*時*分*秒
    c2.setMaxAge(5*60);
    c3.setMaxAge(120);
    response.addCookie(c);
    response.addCookie(c2);
    response.addCookie(c3);
    out.print("<h3>설정완료</h3>");
    %>
</body>
</html>
cs


L02GetCookie.jsp에서 쿠키를 가져오기!

예제 2. L02GetCookie.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>쿠키 가져오기</title>
</head>
<body>
    <h1>쿠키 가져오기</h1>
    <%
    Cookie[] cookies = request.getCookies();
    for(Cookie cookie : cookies){
    %>
    <h3><%=cookie.getName() %>:<%=cookie.getValue() %></h3>
    <%    
    }
     %>
     <hr>
     <h3>세션아이디: <%=session.getId() %>    </h3>
     <!-- Client가 최초 접속시 Session과 Cookie가 생성되는데 쿠키는 세션아이디를 가진다. -->     
     <h3>쿠키는 웹사이트에 접속할 때 생성되는 정보를 담는 임시 파일이다.(클라이언트 컴퓨터에 저장됨)</h3>
     <h3>일반적으로 4kb이하의 크기로 생성된다.</h3>
     <h3>쿠키의 원래 목적은 사용자의 정보를 유지시키고, 접속시 바로 로그인되도록 하기 위해</h3>
     <h3>최근 대부분의 브라우저는 이 쿠키를 개인정보 유출에 취약하다고 판단. 쿠키를 거부</h3>
     <h3>쿠키를 이용해서 로그인 유지하는 것은 위험하다 -> 단점</h3>
     <h3>쿠키는 서버에 요청(request)에 포함된다. 때문에 쿠키가 많으면 요청이 느려진다.</h3>
     <h3>세션은 유지, 쿠키는 저장 -> 보안은 세션이 좋다.</h3>
</body>
</html>
cs


L03RemoveCookie.jsp에서 쿠키를 삭제하자

예제 3. L03RemoveCookie.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>쿠키 삭제하기</title>
</head>
<body>
    <h1>쿠키의 maxAge를 0으로 만들어서 삭제</h1>
    
    <%
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie : cookies){
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            //response는 서버에서 클라이언트에 보내는 최종 응답
            //page가 모두 loading 될 때 응답이 완료된다.
        }
        out.print("삭제완료");
        Cookie[] cookies2 = request.getCookies();
        //이때 request 객체는 response가 되기 전 객체이기 때문에 cookie가 이전 상태의 cookie 이다.
        for(Cookie cookie : cookies2){
        %>
        <h3><%=cookie.getName() %>:<%=cookie.getValue() %></h3>
        <%    
        }//아직 완료된 상태가 아니기 때문에 출력이 된다. 새로고침
    %>
        
</body>
</html>
cs


L04LastDate.jsp에서 마지막으로 접속한 날짜 알아보기

예제 4. L04LastDate.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>마지막 방문일을 알아보자</title>
</head>
<body>
    <h1>lastDate 쿠키를 만들어서 방문일을 담자</h1>
    <%
    Cookie lastDate = null;
    String nowDate = ""+System.currentTimeMillis();
    //cookie에 value로 문자열을 저장하기 위해
    //lastDate라는 cookie가 없으면 최초 방문 -> lastDate 쿠키를 만든다.
    //최초 방문이면 "처음 방문입니다." 라는 메시지를 출력
    //최초 방문일이 아니면 언제 접속했는지 출력한다.
    //오랜만에 접속 시 비밀번호를 바꾸게 한다.
    //강의 페이지 -> 접속하지 않으면 여러가지 메시지
    Cookie[] cookies = request.getCookies();
    if(cookies!=null){
        for(Cookie cookie : cookies){
            if(cookie.getName().equals("lastDate")){
                lastDate = cookie;
            }
        
        }
    }
    if(lastDate==null){
    %>
        <h3>환영합니다! 첫 번째 방문입니다.</h3>
    <%    lastDate = new Cookie("lastDate",nowDate);
        lastDate.setMaxAge(365*24*60*60);
        //lastDate.setPath(""); //./-> 기본경로. /-> 절대경로로 지정하지 않기
        //(Localhost:3306/)절대 경로로 지정하면 다른 프로젝트에서도 쿠키가 유효함.
        //(Localhost:3306/L01Cookie/) 상대경로
        response.addCookie(lastDate);
        System.out.println(nowDate);
    }else{
        long conv = new Long(lastDate.getValue()).longValue();
        //문자열 -> long type으로 변경
        Date date = new Date(conv);
        String year = (date.getYear()+1900)+"년";
        String month = (1+date.getMonth())+"월";
        String day = date.getDate()+"일";
        String hour = date.getHours()+"시";
        String min = date.getMinutes()+"분";
        String sec = date.getSeconds()+"초";

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        
        //date.getDay()  요일 0-> 일요일, 6->토요일
        String strDate= year+month+day+hour+min+sec;
    %>
        <h3>당신의 마지막 방문일은 <%=sdf.format(date) %>입니다.</h3>
    <%    
        lastDate.setValue(nowDate);
        response.addCookie(lastDate);
    }
    %>
</body>
</html>
cs

웬만하면 SimpleDateFormat을 이용하자!

'IT story > JSP' 카테고리의 다른 글

[Jsp 강의] L11ELtag  (0) 2016.10.27
[Jsp 강의] L10Bean  (0) 2016.10.27
[Jsp 강의] L08Session  (0) 2016.10.27
[Jsp 강의] L07Template  (0) 2016.10.27
[Jsp 강의] L06Forward  (0) 2016.10.27