java,jsp,spring/JSP
JSP 쿠키
프루트
2022. 8. 15. 11:34
- 쿠키란?
- 사용자의 정보가 PC에 남음 > 쿠키 확인을 통한 서버의 부하 감소
- http 헤더 정보를 통해서 파일을 저장
- 쿠키의 속성
- 웹 서버의 요청이 있으면 확인할 수 있음
- 4kb, 300개의 용량 제한이 있음
- 제한을 넘어서면 제일 오래된것 부터 삭제함
- 메소드
- int getMaxAge() : 쿠키의 사용 기간
- String getName() : 쿠키의 이름
- String getPath() : 쿠키의 경로
- String getValue() : 쿠키의 값
- setMaxAge(int) : 쿠키의 사용 기간 설정
- setPath(String) : 쿠키의 경로 설정
- JSP에서 사용 방법 : request / response 객체 이용
- 쿠키 설정
1. 쿠키생성
Cookie info = new Cookie(”testCookie”,”I am First Cookie!!”);
2. 객체에 속성값 설정
void setPath(java.lang.String uri)
> info.setPath(”/”);
void setMaxAge(int expiry);
> info.setMaxAge(3652460*60);
3. 쿠키 추가
void addCookie(Cookie cookie) response.addCookie(info);
- 쿠키에 저장된 정보를 서버로 읽어오기
- 쿠키 객체 얻어오기
Cookie[] cookies = request.getCookies();
-
- 쿠키 객체에 설정된 속성값 알아내기
for(int i = 0; i<cookies.length; i++){
cookies[i].getName();
cookies[i].getValue();
}
쿠키 생성, 조회, 삭제
[쿠키 조회]
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<center><h3>[ 쿠키의 정보 얻어오는 예제 ]</h3></center>
<hr>
</body>
</html>
<%
Cookie[] cookies = request.getCookies();
out.println("현재 설정된 쿠키의 갯수 => "+cookies.length);
out.println("<br><hr>");
for(int i=0; i<cookies.length; i++){
out.println(i+"번째 쿠키의 이름 =>"+cookies[i].getName());
out.println("<br><br>");
out.println("쿠키에 설정된 값 =>"+cookies[i].getValue());
out.println("<br><hr>");
}
%>
[쿠키 생성]
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<%
Cookie info = new Cookie("testCookie","FirstCookie");
info.setMaxAge(365*24*60*60);
info.setPath("/");
response.addCookie(info);
%>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<h2>쿠키를 처음 설정하는 중입니다....</h2>
</body>
</html>
[쿠키 삭제]
<%
Cookie[] cookies = request.getCookies();
for(int i=0; i<cookies.length; i++){
out.println(i+"번째 쿠키"+cookies[i].getName()+" 삭제<br>");
cookies[i].setMaxAge(0); // 쿠키 저장 기간을 0초로 설정해 삭제
cookies[i].setPath("/");
response.addCookie(cookies[i]);
}
%>
[마지막 방문일 표시 예제]
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%
Cookie lastDate = null;
boolean found = false;
String msg="";
String newValue = ""+System.currentTimeMillis();
Cookie[] cookies = request.getCookies();
for(int i=0; i<cookies.length; i++){
lastDate = cookies[i];
if(lastDate.getName().equals("lastdateCookie")){
found = true;
break;
}
}
if(!found){
msg="처음 방문입니다...";
lastDate = new Cookie("lastdateCookie",newValue);
lastDate.setMaxAge(365*24*60*60);
lastDate.setPath("/");
response.addCookie(lastDate);
} else {
long conv = Long.parseLong(lastDate.getValue());
msg="당신의 마지막 방문 : "+new Date(conv);
lastDate.setValue(newValue);
response.addCookie(lastDate);
}
%>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<h2><%= msg %></h2>
</body>
</html>