使用ActionContext获得session会带来单元测试不好作,所以使用SessionAware可以用通过的Map对象来注入session,这样在单元测试的时候只需要创建一个Map就可以了。这是一种比较推荐的做法
在类中继承implements SessionAware接口后,定义的所以map集合将自动放入到session中,而我们需要调用到的话就直接去session里面的值
public class UAction extends ActionSupport implements SessionAware{
private Map<String,Object> session=new HashMap<String,Object>();
session.put("privileges", privileges);
List<String> privileges = (List<String>) req.getSession().getAttribute("privileges"); //req是request对象
例子:
LogionAction.Java文件如下:
package com.xujun.webwork.action;
import com.opensymphony.xwork.Action;
import com.opensymphony.webwork.interceptor.SessionAware;
import java.util.Map;
public class LoginAction implements Action,SessionAware{
private Map mySession;
public String execute() throws Exception
{
mySession.put("username", "xujunSessionAware");
return this.SUCCESS;
}
public void setSession(Map session) {
this.mySession = session;
}
}
xwork.xml配置如下,注意interceptor-ref 名称的大小写:
<!DOCTYPE xwork PUBLIC "-//OpenSymphony Group//XWork 1.0//EN"
"http://www.opensymphony.com/xwork/xwork-1.0.dtd">
<xwork>
<include file="webwork-default.xml" />
<package name="default" extends="webwork-default">
<action name="login" class="com.xujun.webwork.action.LoginAction">
<result name="success" type="dispatcher">
<param name="location">/main.jsp</param>
</result>
<interceptor-ref name="completeStack"></interceptor-ref>
</action>
</package>
</xwork>
main.jsp文件如下:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="ww" uri="webwork"%>
<html>
<body>
<p align="center">Login Success!</p>
<p align="center">Welcome!
<ww:property value="#session['username']"/>
</p>
</body>
</html>