본문 바로가기

Java, Spring/08일

8일차 4 - Cookie (1)

cookie

- session과는 반대로 클라이언트 브라우저에 저장하지..

- 4kb초과하면 안되고 한 사이트당 20개 이하..

 

쿠키에 절대 중요한 정보를 넣으면 안돼. 인코딩해서 읽을 수 있고. 패킷스나이퍼같은걸로 채갈 수도 있거든..

로그인 상태인지 체크해놓으면 껏다 켜도 자동 로그인되는 사이트있자나.. 어디다 저장할까? 암호화된 쿠키에 넣어놓는거지. 그래도 게임방같은데선 하지마..

 

session은 jsp에 내장되있어서 session. 하고 바로 사용가능하지만

cookie는 바로 못쓰고 instance를 만들어야해.

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	Cookie cookie = new Cookie("id", "seotaiji");
	cookie.setMaxAge(10); 	//쿠키 유지시간. 초단위. 최초접속시간부터
	
	response.addCookie(cookie);
%>
<!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.getName() %><br/>
쿠키의 값 : <%=cookie.getValue() %><br/>
쿠키의 유지시간 : <%=cookie.getMaxAge() %><br/>
<a href="useCookie.jsp">쿠키 확인</a>
</body>
</html>

cookie.setMaxAge(10);

  • 초단위. 최초 접속시간부터 (session은 최종시간부터)
  • ex)한달 : 60*60*24*30
  • -1 : 쿠키값을 브라우저 닫을 때까지 유지
  • 0 : 기존 쿠키값을 삭제할 때(만듦과 동시에 삭제하는식)

<%@ 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>Insert title here</title>
</head>
<body>
<%
	Cookie[] cookies = request.getCookies();
	if (cookies != null){
		int cook_len = cookies.length;
		
		for(int i=0; i<cook_len; i++){
 			if(cookies[i].getName().equals("id")) {
				out.println("항목 id의 값은" + cookies[i].getValue());
			}
		}
	}
%>
</body>
</html> 

useCookie.jsp에서 if(cookies[i].getName().equals("id"))를 주석처리하면 쿠키하나가 더 보여..

각 서버마다 접속한 클라이언트의 정보를 체크하기 위해서 특정한 시간과 접속한 컴퓨터의 식별id를 섞어서 유니크한 키값의 쿠키를 만들어놓는단다. 브라우저가 하나라도 켜져있다면 계속 남아있어.

 

쿠키는 세션같이 이름을 가지고 바로 찾는 그런거(session.getAttribute(“id”)이런거) 없이 루프돌려서 비교해야해. 역시 좀 불편해..

 

그리고 한글처리 해줘야해.  (안하면 에러나)

요청이나 응답개체 자체에서 반드시 인코딩, 디코딩해줘야해..

 
<%@page import="java.net.URLDecoder"%>
<%@page import="java.net.URLEncoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	Cookie cookie = new Cookie("id", URLEncoder.encode("서태지", "UTF-8"));
	cookie.setMaxAge(10); 	//쿠키 유지시간. 초단위. 최초접속시간부터
	
	response.addCookie(cookie);
%>
<!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.getName() %><br/>
쿠키의 값 : <%=URLDecoder.decode(cookie.getValue(),"UTF-8") %><br/>
쿠키의 유지시간 : <%=cookie.getMaxAge() %><br/>
<a href="useCookie.jsp">쿠키 확인</a>
</body>
</html>

<%@page import="java.net.URLDecoder"%>
<%@ 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>Insert title here</title>
</head>
<body>
<%
	Cookie[] cookies = request.getCookies();
	if (cookies != null){
		int cook_len = cookies.length;
		
		for(int i=0; i<cook_len; i++){
 			if(cookies[i].getName().equals("id")){
				out.println(
					"항목 id의 값은" + 
					URLDecoder.decode(cookies[i].getValue(),"UTF-8"));
			}
		}
	}
%>
</body>
</html> 

 

다른 쿠키의 예제 하나 더 볼까

 
<%@page import="java.net.URLDecoder"%>
<%@ 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>Insert title here</title>
</head>
<body>
<h1>Cookie Test</h1>
<a href="cookieMake.jsp">[쿠키 값 생성]</a>
<a href="cookieRemove.jsp">[쿠키 값 삭제]</a>
<hr/>
<%
	Cookie[] cookies = request.getCookies();
	String id = null;
	String name = null;
	
	if (cookies != null) {
		int cook_len = cookies.length;
		for(int i=0; i<cook_len; i++ ) {
			if(cookies[i].getName().equals("id")){
				id = cookies[i].getValue();
			}
			if(cookies[i].getName().equals("name")){
				name = URLDecoder.decode(
						cookies[i].getValue(), 
						"UTF-8");
			}
		}		
	}
%>
id : <%= (id==null)? "id값이 없습니다" : id %><br/>
name : <%= (name==null)? "name값이 없습니다" : name %><br/>
</body>
</html>

<%@page import="java.net.URLEncoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	Cookie cookie1 = new Cookie("id", "seotaiji");
	cookie1.setMaxAge(-1); 	// 쿠키 값은 브라우저를 닫을때 까지 유지
	response.addCookie(cookie1);

	Cookie cookie2 = new Cookie(
			"name", 
			URLEncoder.encode("정현철", "UTF-8"));
	cookie2.setMaxAge(-1); 	// 쿠키 값은 브라우저를 닫을때 까지 유지
	response.addCookie(cookie2);
%>
<!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>
<% response.sendRedirect("cookieApp.jsp"); %>
</body>
</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	Cookie cookie1 = new Cookie("id", "seotaiji");
	cookie1.setMaxAge(0); // 쿠키 값 삭제
	response.addCookie(cookie1);

	Cookie cookie2 = new Cookie("name", "junghyunchul");
	cookie2.setMaxAge(0); // 쿠키 값 삭제
	response.addCookie(cookie2);
%>
<!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>
<% response.sendRedirect("cookieApp.jsp"); %>
</body>
</html>

 

'Java, Spring > 08일' 카테고리의 다른 글

8일차 2 - 화면분할(파일분할)  (0) 2012.09.20
8일차 3 - session  (0) 2012.09.20
8일차 5 - Cookie (2)  (0) 2012.09.20
8일차 6-2 - login Model2로 만들기 (1)  (0) 2012.09.20
8일차 7 - login Model2로 만들기 (2)  (0) 2012.09.20