现在的位置: 首页 > 综合 > 正文

跟踪用户状态

2018年05月23日 ⁄ 综合 ⁄ 共 1050字 ⁄ 字号 评论关闭

当一个用户登录成功后,需要将用户的用户名添加为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之间的转换。

public String execute() throws Exception {  //处理用户请求的execute方法
         if (getUsername().equals("scott") && getPassword().equals("tiger") ) {
            ActionContext ctx = ActionContext.getContext();
           //将当前登录的用户名保存到Session
            Map session = ctx.getSession();
            session.put("username",getUsername());
            return SUCCESS;
        } else {
            return ERROR;
          }
}

上面的代码仅提供了Action类的execute方法,该Action类的其他部分与前面的Action类代码完全一样。在上面的Action类通过ActionContext设置了一个Session属性:user。为了检验我们设置的Session属性是否成功,我们修改welcome.jsp页面,在welcome.jsp页面中使用JSP 2.0表达式语法输出Session中的user属性。

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

 

抱歉!评论已关闭.