当一个用户登陆成功后,须要将用户的用户名添加为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方法代码以下:html
- //处理用户请求的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;
- }
- }
为了检验咱们设置的Session属性是否成功,咱们修改welcome.jsp页面,在welcome.jsp页面中使用JSP 2.0表达式语法输出Session中的user属性。java
- <%@ page language="java" contentType="text/html; charset=GBK"%>
- <html>
- <head>
- <title>成功页面</title>
- </head>
- <body>
- 欢迎,${sessionScope.user},您已经登陆!
- </body>
- </html>