Cookie
: HTTP 프로토콜은 비 연결 지향 통신 프로토콜이다. 즉,
클라이언트의 요청에 서버가 응답한 후 연결을 끊는다.
쿠키는 사용자의 정보를 지속적으로 유지하기 위한 방법으로
웹 서버가 응답 할 때, HTTP 헤더에 쿠키 정보를 포함하여 보내고, 클라이언트의 컴퓨터 하드디스크에 사용자 정보를 저장한다.
(Session은 서버에 저장)
JSP에서 쿠키 사용법
- request 객체 : 저장되어 있는 쿠키의 값을 가져올 때
- response 객체 : 쿠키를 설정하고자 할 때
- 쿠키 생성 : Cookie info = new Cookie(”testCookie”,”I am First Cookie”);
- 쿠키 객체에 속성 값 설정
: void setMaxAge(int expriy); 쿠키의 유효기간 설정 - response.addcookie(Cookie cookie);
Cookie값 가져오기
request.getCookies(); 메소드를 통해 가져온 쿠키들을 Cookie[] 배열에 저장하고,
해당 쿠키의 메소드들을 통해 쿠키의 속성들을 가져온다.
쿠키를 통해 마지막으로 방문한 날짜를 출력하는 예제
Cookie lastDate=null;
String msg=""; //화면 출력 메시지
boolean found = false; // 첫 방문 여부
String newValue= ""+System.currentTimeMillis(); //현재 시간 정보 값(Long타입이므로 ""더하면 편하게 형변환 됨)
Cookie[] cookies = request.getCookies();
if(cookies !=null){ //만약 쿠키가 있으면
System.out.print("@# cookies.length===>"+cookies.length);
for(int i=0;i<cookies.length;i++){ // 반복하면서 쿠키이름이 lastDateCookie가 있으면 첫방문이 아니다.
lastDate = cookies[i];
if(lastDate.getName().equals("lastDateCookie")){ // 첫 방문시 lastDateCookie의 found값을 true로 바꿔줌.
found=true;
break;
}
}
// if/else 처음/아닐때(lastDate 쿠키 객체에 값이 있음)
// 첫방문이든 아니든 lastDate 쿠키 객체를 만들어 줌
if(!found){ // 처음 방문이라면 쿠키를 만들어 준다.
msg="처음 방문 입니다.";
// 처음 방문일때 lastDateCookie 이름으로 시간정보를 저장
lastDate =new Cookie("lastDateCookie",newValue);
lastDate.setMaxAge(365*24*60*60);
lastDate.setPath("/");
response.addCookie(lastDate);
}else {
//lastDate 시간 정보를 Long으로 감싸서 가져옴
long conv = Long.parseLong(lastDate.getValue());
msg="당신의 마지막 방문 : "+new Date(conv); //Date객체로 현재시간정보를 계산해서 의미있는 시간정보로 출력해준다.
lastDate.setValue(newValue); //다음에 또 방문할수있으니 새로 시간값 넣어줌
response.addCookie(lastDate);
}
}
for(int i=0;i<cookies.length;i++){
out.print(i+"번째 쿠키의 이름=>"+cookies[i].getName());
out.print("<br><hr>");
out.print("쿠키의 설정된 값=>"+cookies[i].getValue());
out.print("<br><hr>");
}
출력화면
'Category > JSP&Servlet' 카테고리의 다른 글
[JSP] JDBC를 이용해서 JSP와 연동하기 (0) | 2023.11.29 |
---|---|
Session 이란? (0) | 2023.11.27 |
2. Servlet에서 데이터 처리하기 (1) | 2023.11.22 |
1. JSP& Servlet 란? (0) | 2023.11.22 |
[JSP] JSP에서 Javascript 사용하기 (0) | 2023.11.10 |