// 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닫기
'웹프로그램' 카테고리의 다른 글
| JSP 오라클8i 글자수 무제한 게시판소스 (0) | 2009.06.09 | 
|---|---|
| JSP 동적 이미지(실시간 그래프) 생성하기 (0) | 2009.06.09 | 
| JSP UTF-8로 파일 저장하기 (0) | 2009.06.09 | 
| JSP 파일 업로드 (0) | 2009.06.09 | 
| JSP DB 연결하기 (0) | 2009.06.09 | 
| ASP equivalent of PHP's iconv (0) | 2009.06.09 | 
| BeginTrans, CommitTrans 및 RollbackTrans 메서드 (ADO) (0) | 2009.06.09 | 
| 자바스크립트에서 confirm() 을 사용할 경우 확인, 취소 로 나오는 버튼을 Yes, No 로 바꾸기 (0) | 2009.05.08 |