L07 쿠키로 값 전달
2016. 10. 27. 17:49ㆍProgramming/JSP
**배운 것**
1) 쿠키 생성
Cookie c = new Cookie("id", "jspLesson");
2) 유효시간 설정 후 쿠키에 저장
c.setMaxAge(365*24*60*60); //1년 = 일*시*분*초
response.addCookie(c);
3) 쿠키 메소드
setPath(): 쿠키 사용의 유효 디렉토리 설정
setVersion(): 쿠키 버전 설정
getName(): 쿠키 이름 얻기
getValue(): 쿠키 값 얻기
4) 첫 방문/아닌 경우 분기(if) 만들어
lastTime(방문 시간) 쿠키에 저장
<index.jsp: 메인 화면>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <%@ 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> | cs |
<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 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> <% //쿠키는 브라우저에 저장되는 객체(마치 파일처럼) //세션과 달리 브라우저 꺼져도 남아 있음(but 시간 지나면 사라짐) //쿠키를 생성하고 response 객체에 담으면 저장 완료 Cookie c = new Cookie("id", "jspLesson");//생성과 동시에 파라미터 저장 Cookie c2 = new Cookie("pw", "admin1234"); Cookie c3 = new Cookie("name", "ckm"); //만약 유효시간 설정 안 하면 브라우저 종료시 삭제됨 c.setMaxAge(365*24*60*60); //1년 = 일*시*분*초 response.addCookie(c); response.addCookie(c2); response.addCookie(c3); out.print("<h3>설정완료</h3>"); %> </body> </html> | cs |
<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 31 32 33 34 35 36 | <%@ 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(int i=0; i<cookies.length; i++){ out.print("<h3>"+cookies[i].getName()+":"+cookies[i].getValue()+"<h3>"); //다른 방식 //for(Cookie cookie : cookies){ //out.print("<h3>"+cookie.getName()+":"+cookie.getValue()+"<h3>"); } %> <hr> <h3>세션아이디: <%=session.getId()%></h3> <!--클라이언트가 최초 접속시 session과 cookie가 생성되는데 쿠키는 세션 아이디를 가짐--> <h3>쿠키는 웹사이트에 접속할 때 생성되는 정보를 담는 임시 파일이다.</h3> <h3>일반적으로 4kb 이하의 크기로 생성된다.</h3> <h3>쿠키의 원래 목적은 사용자의 정보를 유지시키고 접속시 바로 로그인되도록 하기 위해</h3> <h3>쿠키의 단점</h3> <h3>1. 쿠키는 요청(request)에 포함되기 때문에 쿠키가 많으면 요청이 느려짐</h3> <h3>2. 세션은 유지, 쿠키는 저장 -> 보안은 세션이 좋다.</h3> </body> </html> | cs |
<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 | <%@ 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 a : cookies){ //[뽑을 데이터타입] [변수명]: [배열명] a.setMaxAge(0); response.addCookie(a); //response는 서버에서 클라이언트에 보내는 최종 응답 //page가 모두 loading 될 때 응답이 완료됨 } %> <h1>삭제 완료</h1> </body> </html> | cs |
<L03RemoveCookie.jsp:첫 방문>
<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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import ="java.util.Date, java.text.SimpleDateFormat" %> <!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라는 쿠키가 없으면 최초 방문 -> lastDate 쿠키를 만든다. //최초 방문이면 "처음 방문입니다." 라는 메시지를 출력 //최초 방문이 아니면 언제 접속했는지 lastDate를 출력 //활용 예 //1) 오랜만에 접속시 비밀번호를 바꾸게 한다. //2) 강의 페이지 -> 접속하지 않으면 여러 가지 메시지 Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie a : cookies) { if(a.getName().equals("lastDate")){ lastDate = a; //최초 방문이 아님 } } } //첫 방문인 경우(일단 출력 후 현재시간(nowDate) 쿠키에 저장) if(lastDate==null){ out.print("<h3>처음 방문입니다.</h3>"); lastDate = new Cookie("lastDate", nowDate); lastDate.setMaxAge(365*24*60*60); response.addCookie(lastDate); //첫 방문 아닌 경우 }else{ //문자열 -> long type으로 변경 long conv = new Long(lastDate.getValue()).longValue(); Date date = new Date(conv); //Date에서 년월일시분 추출 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); out.print(sdf.format(date)); //마지막 방문일 업데이트 lastDate.setValue(nowDate); response.addCookie(lastDate); } %> </body> </html> |
'Programming > JSP' 카테고리의 다른 글
L09 EL 태그 활용, 내장 객체 종류, 예외처리 (0) | 2016.10.28 |
---|---|
L08 Bean으로 값(parameter) 전달 (0) | 2016.10.27 |
L06 세션으로 값 전달(2/2) ~로그인/로그아웃 (0) | 2016.10.27 |
L06 세션으로 값 전달(1/2) (0) | 2016.10.27 |
L05 Template (0) | 2016.10.26 |