(一)通过ActionContext
为了避免与Servlet API耦合在一起,方便Action类做单元测试,Struts 2对HttpServletRequest、HttpSession和ServletContext进行了封装,构造了三个Map对象来替代这三种对象,在Action中,直接使用HttpServletRequest、HttpSession和ServletContext对应的Map对象来保存和读取 数据。可以通过com.opensymphony.xwork2.ActionContext类来得到这三个对象。ActionContext是Action执行的上下文,保存了很多对象如parameters、request、session、application和locale等。通过ActionContext类获取Map对象的方法为:
public class TestAction1 extends ActionSupport{
private Map<String,Object> request;
private Map<String, Object> session;
private Map<String, Object> application;
public TestAction1() {
// TODO Auto-generated constructor stub
this.request = (Map)ActionContext.getContext().get("request");
this.session = ActionContext.getContext().getSession();
this.application = ActionContext.getContext().getApplication();
}
}
(二)控制反转
Action类还有另一种获得ServletAPI的解耦方式,这就是我们可以让他实现某些特定的接口,让Struts2框架在运行时向Action实例注入request、session和application对象。这种方式也就是控制反转方式,与之对应的三个接口和它们的方法如下所示:
public class TestAction2 extends ActionSupport implements RequestAware, SessionAware,ApplicationAware{
private static final long serialVersionUID = 1L;
private Map<String,Object> request;
private Map<String, Object> session;
private Map<String, Object> application;
@Override
public void setApplication(Map<String, Object> application) {
// TODO Auto-generated method stub this.application = application;
}
@Override
public void setSession(Map<String, Object> session) {
// TODO Auto-generated method stub
this.session = session;
}
@Override
public void setRequest(Map<String, Object> request) {
// TODO Auto-generated method stub
this.request = request;
}
public TestAction2() { // TODO Auto-generated constructor stub }
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
System.out.println("TestAction2 execute...");
this.request.put("reqAttr", "reqDirect");
this.session.put("sessionAttr", "sessionDirect");
this.application.put("applicationAttr", "applicationDirect");
return SUCCESS; }
}