为了访问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之间的转换。
//处理用户请求的execute方法
public String execute() throws Exception
{
//当用户请求参数的username等于scott,密码请求参数为tiger时,返回success字符串
//否则返回error的字符串
if (getUsername().equals("scott")
&& getPassword().equals("tiger") )
{
//通过ActionContext对象访问Web应用的Session
ActionContext.getContext().getSession().put("user" , getUsername());
return SUCCESS;
}
else
{
return ERROR;
}
}
上面的代码仅提供了Action类的execute方法,该Action类的其他部分与前面的Action类代码完全一样。在上面的Action类通过ActionContext设置了一个Session属性:user。