http 세션 (1)

💻 Programming/JSP

[JSP] Session ( 세션 )

이번에는 JSP로 세션을 다루는 법에 대해서 배워보도록 하겠습니다. HTTP는 "stateless" 프로토콜입니다.  무슨 말이냐하면 말이죠, 클아이언트(웹브라우저)가 웹페이지를 불러올때마다 클라이언트는 웹서버로 별도의 커넥션을 맺습니다. 그리고 이전 클라이언트의 접속에 대한 어떠한 정보도 자동으로 기록하지는 않습니다. 

어쨌든 세션이라는 것은 바로 웹브라우저가 웹서버와 연결이 될때 생기는 것인데, 이 세션을 유지하는 방법에는 여러가지가 있답니다.  

1. Cookies

쿠키에 세션ID를 저장하는 식으로 세션을 관리할 수는 있겠지만 브라우저에서 쿠키사용 제한 설정이 있을 수 있기때문에 세션을 쿠키를 이용해서 관리한다는 것은 좋은방법이 아닙니다.

 

 

2. Hidden Form Fields

 

웹서버는 hidden HTML form field에 unique session ID를 넣어서 아래처럼 전송할 수 있습니다.

<input type="hidden" name="sessionid" value="12345">

form이 전송될 때 세션ID와 값을 넘겨주는거죠. 브라우저에서 이 정보를 웹서버에 보내면 이 정보를 가지고 웹서버에서는 다른 브라우저에서 접속한 것인지를 판단할 수 있게 됩니다. 하지만 이 역시 좋은 방법은 아니죠. <a> 태그를 이용해서 링크를 타고 들어오는 경우에는 저 form데이타를 전송하지 않거든요.

3. URL Rewriting

URL 끝에 세션에 대한 정보를 추가할 수도 있습니다. 그리고 서버는 그 정보를 가지고 세션을 비교할 수 있겠죠.

예를들면, http://tutorialspoint.com/file.htm;sessionid=12345 이렇게 요청을 보내면 서버에서 sessionid=12345부분에 대한 정보를 가지고 웹서버의 세션정보와 비교를 하는거죠.

URL rewriting 은 세션을 관리하기위한 방법들 중에서는 그나마 좋은 방법이긴 합니다. 브라우저가 쿠키사용을 안할때도 사용가능한 방법이니까요. 하지만 역시 결점이 있습니다. 세션ID를 동적으로 매번 생성해줘야 하기 때문입니다. 정적인 HTML페이지라도 말이죠.  


The session Object:

위 세가지 방법 이외에도 JSP는 HttpSession 인터페이스를 사용할 수 있습니다. 기본적으로 JSPs는 세션을 추적하게 되어있으며 새로운 HttpSession 객체가 새로운 클라이언트들이 접속할 때마다 자동으로 생성됩니다. 세션 추적 기능을 끄려면 page directive의 세션 속성을 false로 세팅해줘야 합니다. 아래 처럼 말이죠.

<%@ page session="false" %>

JSP engine은 JSP개발자들에게 HttpSession 객체를 통해서 session에 접근할 수 있도록 해줍니다. session 객체가 기본적으로 제공이 되기 때문에 개발자들은 궂이 세션객체를 생성하거나 getSession() 메소드를 이용해서 얻어올 필요가 없습니다.

웹애플리케이션을 작성하고 있다면 그냥 세션을 파라미터로 받아서 쓰면 되는 겁니다. 

 

다음은 세션 객체가 가지고 메소드 목록입니다. 어떤 메소드들이 있는지 한번 살펴볼까요~

 

S.N.Method & Description
1public Object getAttribute(String name)
This method returns the object bound with the specified name in this session, or null if no object is bound under the name.
2public Enumeration getAttributeNames()
This method returns an Enumeration of String objects containing the names of all the objects bound to this session.
3public long getCreationTime()
This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
4public String getId()
This method returns a string containing the unique identifier assigned to this session.
5public long getLastAccessedTime()
This method returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.
6public int getMaxInactiveInterval()
This method returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.
7public void invalidate()
This method invalidates this session and unbinds any objects bound to it.
8public boolean isNew(
This method returns true if the client does not yet know about the session or if the client chooses not to join the session.
9public void removeAttribute(String name)
This method removes the object bound with the specified name from this session.
10public void setAttribute(String name, Object value) 
This method binds an object to this session, using the name specified.
11public void setMaxInactiveInterval(int interval)
This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session.


Session Tracking Example:

다음 예제는 HttpSession 객체를 이용하여 세션의 생성시간과 마지막 접근시간 정보를 가져오는 방법에 대해서 설명해주고 있습니다.  

<%@ page import="java.io.*,java.util.*" %> <% // Get session creation time. Date createTime = new Date(session.getCreationTime()); // Get last access time of this web page. Date lastAccessTime = new Date(session.getLastAccessedTime()); String title = "Welcome Back to my website"; Integer visitCount = new Integer(0); String visitCountKey = new String("visitCount"); String userIDKey = new String("userID"); String userID = new String("ABCD"); // 처음 접속한 방문자라면 세션을 생성합니다. if (session.isNew()){ title = "Welcome to my website"; session.setAttribute(userIDKey, userID); session.setAttribute(visitCountKey, visitCount); } visitCount = (Integer)session.getAttribute(visitCountKey); visitCount = visitCount + 1; userID = (String)session.getAttribute(userIDKey); session.setAttribute(visitCountKey, visitCount); %> <html> <head> <title>Session Tracking</title> </head> <body> <center> <h1>Session Tracking</h1> </center> <table border="1" align="center"> <tr bgcolor="#949494"> <th>Session info</th> <th>Value</th> </tr> <tr> <td>id</td> <td><% out.print( session.getId()); %></td> </tr> <tr> <td>Creation Time</td> <td><% out.print(createTime); %></td> </tr> <tr> <td>Time of Last Access</td> <td><% out.print(lastAccessTime); %></td> </tr> <tr> <td>User ID</td> <td><% out.print(userID); %></td> </tr> <tr> <td>Number of visits</td> <td><% out.print(visitCount); %></td> </tr> </table> </body> </html>

 main.jsp​에 위 코드를 넣고 http://localhost:8080/main.jsp 를 호출해보세요. 서버 실행시키는 것 잊어먹지 마시구요~ ^___^ 

Welcome to my website

Session Infomation

Session infovalue
id0AE3EC93FF44E3C525B4351B77ABB2D5
Creation TimeTue Jun 08 17:26:40 GMT+04:00 2010
Time of Last AccessTue Jun 08 17:26:40 GMT+04:00 2010
User IDABCD
Number of visits0

 

 

위와같은 페이지가 나오나요??

 

다시한번 호출 해 볼까요??

 

Welcome Back to my website

Session Infomation

info typevalue
id0AE3EC93FF44E3C525B4351B77ABB2D5
Creation TimeTue Jun 08 17:26:40 GMT+04:00 2010
Time of Last AccessTue Jun 08 17:26:40 GMT+04:00 2010
User IDABCD
Number of visits1


위와 같은 결과가 나오나요? Welcome 메시지가 Welcome Back 메시지로 바뀌었네요. ^__^ 

 

 

이제 세션 데이타를 삭제하는 방법을 알아볼까요??​​

 

Deleting Session Data:

사용자의 세션 데이타로 해야되는 작업을 모두 완료하였다면 아래와 같은 작업을 마지막으로 해줄 수 있습니다.

  • 특정 속성 삭제 : removeAttribute(String name) 메소드를 이용해서 세션의 특정 속성값만 삭제할 수 있습니다. 

  • 세션 삭제 : invalidate() 메소드를 호출하여 세션 전체를 무효화 시킬 수 있습니다. 세션을 끊는다고 표현하죠. 

  • 세션 타임아웃 설정 : setMaxInactiveInterval(int interval) 메소드를 이용하여 세션별로 타임아웃을 설정할 수 있습니다.

  • 사용자 로그아웃 : servlets 2.4를 지원하는 서버라면 logout 을 호출하여 사용자를 로그아웃시키고 모든 세션을 무효화 시킬 수 있습니다.  

  • web.xml 설정 : Tomcat을 사용중이라면 web.xml 파일에서 아래처럼 타임아웃 시간을 설정할 수도 있습니다.

<session-config> <session-timeout>15</session-timeout> </session-config>

여기서 타임아웃 시간의 단위는 분 단위이며 톰캣의 기본 타임아웃인 30 분을 오버라이드하여 적용됩니다.

서블릿의 getMaxInactiveInterval( )메소드는 초단위로 타임아웃 시간을 가져옵니다. 따라서 web.xml 파일에 15 분으로 설정되어있다면  getMaxInactiveInterval( ) 메소드는 900 ( 15분 * 60초 )를 반환하게 됩니다 .

 

 

 

 

Reference : http://www.tutorialspoint.com/jsp/jsp_session_tracking.htm