본문 바로가기

카테고리 없음

Session Handling

Struts2에서 HttpSession 다루는 예

ActionContext.getContext().getSession()과 ServletActionContext.getRequest().getSession()을 이용하여 세션을 다룰 수 있다

- ActionContext.getContext().getSession() : HttpSession객체 안에 저장된 데이터를 맵에 저장하여 리턴해 준다.
- ServletActionContext.getRequest().getSession() : Servlet, JSP에서 사용되는 HttpSession객체를 리턴한다.

HttpSession 객체에 데이터를 저장하는 경우 (로그인)
Map session = ActionContext.getContext().getSession();
      session.put("logged-in","true");


HttpSession 객체에 저장된 데이터를 삭제하는 경우(로그아웃)
Map session = ActionContext.getContext().getSession();
    session.remove("logged-in");


from: Struts 2 API Docs
public class ActionContext extends Object
implements Serializable

The ActionContext is the context in which an Action is executed.
Each context is basically a container of objects an action needs for execution like the session, parameters, locale, etc.

The ActionContext is thread local which means that values stored in the ActionContext are unique per thread.
See the ActionContext.ActionContextThreadLocal class for more information.
The benefit of this is you don't need to worry about a user specific action context, you just get it:

    ActionContext context = ActionContext.getContext();

Finally, because of the thread local usage you don't need to worry about making your actions thread safe.


static ActionContextgetContext()
          Returns the ActionContext specific to the current thread.

 MapgetSession()
          Gets the Map of HttpSession values when in a servlet environment or a generic session map otherwise.

MapgetParameters()
          Returns a Map of the HttpServletRequest parameters when in a servlet environment or a generic Map of parameters otherwise.





SessionTest.java
package struts2test;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.*;
import java.util.*;
public class SessionTest extends ActionSupport {
  public String execute() throws Exception {
  Map session = ActionContext.getContext().getSession();
  session.put("data", "Hello");
  return SUCCESS;
  }
}

session.jsp


<%@page contentType="text/html;charset=KSC5601"%>
<HTML>
 <HEAD>
  <TITLE>Action클래스와 JSP사이의 세션 테스트 </TITLE>
 </HEAD>
 <BODY><center>
 Action 클래스에서 세션에 설정한 값:
  <%=session.getAttribute("data")%> <br>
  <s:property value="%{#session.data}"/> <br>
  <s:property value="#session.data"/> <br>
<s:property value="#session"/> <br>
</center>
 </BODY>
</HTML>



struts.xml

<action name="SessionTest"  class="struts2test.SessionTest">
 <result>/pages/session.jsp</result>
</action>


사용자 삽입 이미지