Sio's Programming
JSP 세션 본문
세션이란?
세션도 쿠키와 마찬가지로 서버와의 관계를 유지하기 위한 수단 입니다.
단, 쿠키와 달리 클라이언트의 특정 위치에 저장되는 것이 아니라, 서버상에 객체로 존재 합니다.
따라서 세션은 서버에서만 접근이 가능하여 보안이 좋고, 저장할 수 있는 데이터에 한계가 없습니다.
세션 문법
세션은 클라이언트의 요청이 발생하면 자동생성 됩니다. 그리고 session 이라는 내부 객체를 지원하여 세션의 속성을 설정 할 수 있습니다.
클라이언트 요청 -> session 자동생성 -> session 속성 설정
setAttribute() : 세션에 데어터를 저장
getAttribute() : 세션에서 데이터를 얻습니다.
getAttributeNames() : 세션에 저장되어 있는 모든 데이터의 이름(유니크한 키값)을 얻습니다
getId() : 자동 생성된 세션의 유니크한 아이디를 얻습니다.
isNew() : 세션이 최초 생성되었는지, 이전에 생성된 세션인지를 구분
getMaxInactiveInterval() : 세션의 유효시간을 얻습니다. 가장 최근 요청시점을 기준으로 카운트 됩니다.
removeAttrivute() : 세션에서 특정 데이터 제거 합니다.
Invalidate() : 세션의 모든 데이터를 삭제 합니다.
로그인 예제
login.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <!DOCTYPE html> <html> <head> <meta charset="EUC-KR"> <title>Insert title here</title> </head> <body> <form action="login.jsp" method="post"> 아이디 : <input type="text" name="id" size="5"> 비밀번호 : <input type="password" name="pw" size="10"><br /> <input type="submit" value="로그인"> </form> </body> </html> | cs |
login.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <%! String id,pw; %> <% id = request.getParameter("id"); pw = request.getParameter("pw"); if(id.equals("abcd") && pw.equals("12345")){ session.setAttribute("id", id); response.sendRedirect("welcom.jsp"); }else{ response.sendRedirect("login.html"); } %> | cs |
welcom.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <% Enumeration enumeration = session.getAttributeNames(); while(enumeration.hasMoreElements()){ String sName = enumeration.nextElement().toString(); String sValue = (String)session.getAttribute(sName); if(sValue.equals("abcd")){ out.println(sValue + "님 안녕하세요." + "<br />"); } } %> <a href="logout.jsp">로그아웃</a> | cs |
logout.jsp
1 2 3 4 5 6 7 8 9 10 11 | <% Enumeration enumeration = session.getAttributeNames(); while(enumeration.hasMoreElements()){ String sName = enumeration.nextElement().toString(); String sValue = (String)session.getAttribute(sName); if(sValue.equals("abcd"))session.removeAttribute(sName); } %> <a href="sessiontest.jsp">sessionTest</a> | cs |
sessiontest.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <% Enumeration enumeration = session.getAttributeNames(); int i = 0; while(enumeration.hasMoreElements()){ i++; String sName = enumeration.nextElement().toString(); String sValue = (String)session.getAttribute(sName); out.println("sName:"+sName+"<br />"); out.println("sValue:"+sValue+"<br />"); } if(i==0)out.println("해당 세션이 삭제 되었습니다."); %> | cs |
'Programming > JSP' 카테고리의 다른 글
| JSP (자바 빈) (0) | 2018.05.09 |
|---|---|
| JSP (예외 페이지, page 지시자 예외처리, web.xml 예외처리) (0) | 2018.05.09 |
| JSP 쿠키 (0) | 2018.05.08 |
| JSP (액션태그,forward, include, param) (0) | 2018.05.08 |
| JSP (request,response) (0) | 2018.05.07 |