// session을 이용한 카운터
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionCounter extends HttpServlet{
static final String Counter_key ="Counter.count";
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException{
// 클라이언트로 부터 세션을 가지고 오는데.
// true 일때만 세션의 객체를 반환합니다.
HttpSession session = req.getSession(true);
res.setContentType("text/html");
PrintWriter pout = new PrintWriter(
new OutputStreamWriter(
res.getOutputStream(),"KSC5601"
)
);
int count =1;
Integer i =(Integer) session.getAttribute(Counter_key);
//만약 그 전에 카운터가 있다면 그 값을 더해줍니다.
if( i != null) {
count=i.intValue()+1;
}//if 문 닫기
// 쿠키관련 시작!!
// 사용자에게 저장된 쿠키를 몽창 가져온다. 그리고 저장된 시간도 가져온당..
Cookie cookies[] = req.getCookies();
Cookie cookie = null;
long cookieDate = 0L;
if(cookies != null) {
cookie = cookies[0];
cookieDate = Long.parseLong(cookie.getValue());
} else {
Cookie coo = new Cookie("TodayCheck", new String(""+System.currentTimeMillis()));
coo.setMaxAge(60*60*24);
res.addCookie(coo);
}
long nowTime = System.currentTimeMillis() - cookieDate;
if(nowTime > 60*60*24*1000) {
// 여기 조금 이상함.. MilliSecond 를 준다고 해서
// 1000을 곱해주기는 했는데 정확한지는 모르겠음.
// API 보고 수정요망..
System.out.println("하루가 지났습니다. 카운트를 증가합니다.");
//새션안에 반환된 카운터의 값을 추가합니다.
session.setAttribute(Counter_key, new Integer(count));
} else {
System.out.println("하루가 안지났습니다. 당신을 증가대상에서 제외합니다~~(개그콘서트버젼)");
}
// Cookie 클래스 관련 끝... 실행하시고 쿠키가 생성되었는지 Cookie 디렉토리에서 확인요망..
pout.println("<html>");
pout.println("<head>");
pout.println("<title> 세션으로 만든 카운터</title>");
pout.println("</head>");
pout.println("<body>");
pout.println("당신의 세션아이디는 <b>"+session.getId()+"</b>");
pout.println("이며 당신의 방문횟수는 <b>"+count+" 째 입니다.</b>");
pout.println("<form method=GET action=""+req.getRequestURI()+"">");
pout.println("<input type=submit value="다시보기">");
pout.println("</form>");
pout.println("</body></html>");
pout.flush();
}// doGet() 닫기
}// SessionCounter닫기
반응형
'JAVA' 카테고리의 다른 글
JAVA 스레드 인터럽트(interrupts), 조인(join) (0) | 2021.12.10 |
---|---|
java 스레드 만들고 시작하기(thread, runnable) (0) | 2021.12.09 |
IP 주소 구하기 (0) | 2021.12.09 |
JAVA 트랜잭션 처리 (0) | 2021.11.28 |
Java 형변환 정리 (0) | 2021.11.28 |
최근댓글