当一个用户登录成功后,需要将用户的用户名添加为Session状态信息。
为了访问HttpSession实例,Struts 2提供了一个ActionContext类,该类提供了一个getSession的方法,但该方法的返回值类型并不是HttpSession,而是 Map。这又是怎么回事呢?实际上,这与Struts 2的设计哲学有关,Struts 2为了简化Action类的测试,将Action类与Servlet API完全分离,因此getSession方法的返回值类型是Map,而不是HttpSession。
虽然ActionContext的getSession返回的不是HttpSession对象,但Struts 2的系列拦截器会负责该Session和HttpSession之间的转换。
为了可以跟踪用户信息,我们修改Action类的execute方法,在execute方法中通过ActionContext访问Web应用的Session。修改后的execute方法代码如下:

 

 
  
  1. //处理用户请求的execute方法 
  2. public String execute() throws Exception { 
  3. //当用户请求参数的username等于scott,密码请求参数为tiger时,返回success字符串 
  4. //否则返回error的字符串 
  5.  if (getUsername().equals("scott") && getPassword().equals("tiger") ) { 
  6. //通过ActionContext对象访问Web应用的Session 
  7. ActionContext.getContext().getSession().put("user" , getUsername()); 
  8.   return SUCCESS; 
  9.  } else { 
  10.   return ERROR; 
  11.  } 
  12.  
  13. }    

 

为了检验我们设置的Session属性是否成功,我们修改welcome.jsp页面,在welcome.jsp页面中使用JSP 2.0表达式语法输出Session中的user属性。

 

 
  
  1. <%@ page language="java" contentType="text/html; charset=GBK"%> 
  2. <html> 
  3. <head> 
  4. <title>成功页面</title> 
  5. </head> 
  6. <body> 
  7. 欢迎,${sessionScope.user},您已经登录! 
  8. </body> 
  9. </html>