Servlet Session

박병주·2022년 12월 28일
0

servlet

목록 보기
5/7

Session

정의

  • 일정 시간동안(기본 30분) 같은 브라우저로부터 들어오는 값을 일정하게 유지시키는 기술
  • 브라우저가 페이지의 방문 시점부터 브라우저 종료 시점 까지 유지
  • 방문자가 웹 서버에 접속해 있는 상태를 하나의 단위로 봄

특징

  • 웹 서버에 저장되는 쿠키(쿠키의 일종임)
  • 웹 브라우저를 닫거나, 서버에서 삭제처리를 했을때만 삭제가 되므로, 쿠키보다 비교적 보안이 좋다.
  • 저장 데이터에 제한이 없다.(서버 용량)
  • 각 클라이언트 고유 Session ID를 부여한다. (서버에서 클라이언트를 구분하는 방법)

Create Session

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // display
        PrintWriter printWriter = response.getWriter();
        printWriter.println("<div>Create Session Servlets</div>");
        // login 
        if("bottlepark".equals(username) && "1234".equals(password)){
            HttpSession httpSession = request.getSession();
            httpSession.setAttribute("username", username);
            httpSession.setAttribute("password", password);
            printWriter.println("<div>"+username+", "+password+"</div>");
        } else {
            printWriter.println("<div>Faild</div>");
        }
        printWriter.close();

Get Session

  • request.getSession()를 사용하여 값을 불러올 수 있다.
        HttpSession httpSession = null;
        String path = null;
        
        if("bottlepark".equals(username) && "1234".equals(password)){
            // login
            httpSession = request.getSession(false);  
            if (httpSession == null){
                httpSession = request.getSession();  
                httpSession.setAttribute("username", username);
                httpSession.setAttribute("password", password);
            }
         }
  • getSession(), getSession(true)
    HttpSession이 존재하면 현재 HttpSession을 반환하고 존재하지 않으면 새로운 세션을 생성
  • getSession(false)
    HttpSession이 존재하면 현재 HttpSession을 반환하고 존재하지 않으면 Null을 반환

Delete Session

  • session.invalidate()
    해당 세션을 없애고 세션에 속해있는 모든 값들을 제거한다.
        HttpSession httpSession = request.getSession();
		
        httpSession.invalidate();
        if(request.getSession(false)==null){
        	System.out.println("session is null");
        }
profile
Developer

0개의 댓글