1、非IoC方式
要获得上述对象,关键Struts 2中com.opensymphony.xwork2.ActionContext类。我们可以通过它的静态方法getContext()获取当前Action的上下文对象。有了这个对象我们想获得其他几个对象就好办了
ActionContext ctx
=
ActionContext.getContext();
Map session = ctx.getSession();
Map session = ctx.getSession();
细心的朋友可以发现这里的session是个map对象在Struts2中底层的session都被封装成了Map类型我们可以直接操作这个map 进行对session的写入和读取操作而不用去直接操作HttpSession对象
另外,org.apache.struts2.ServletActionContext作为辅助类(Helper Class),可以帮助您快捷地获得这几个对象。
HttpServletRequest request
=
ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
HttpSession session = request.getSession();
HttpServletResponse response = ServletActionContext.getResponse();
HttpSession session = request.getSession();
2、IoC方式(这种方式在tapestry中也是这样实现的)
要使用IoC方式,我们首先要告诉IoC容器(Container)想取得某个对象的意愿,通过实现相应的接口做到这点。具体实现
public class IoCServlet
extends
ActionSupport
implements
SessionAware, ServletRequestAware, ServletResponseAware {
private Map session;
private HttpServletRequest servletRequest;
private HttpServletResponse servletResponse;
publicvoid setSession(Map session) {
this .session = session;
}
publicvoid setServletRequest(HttpServletRequest servletRequest) {
this .servletRequest = servletRequest;
}
publicvoid setServletResponse(HttpServletResponse servletResponse) {
this .servletResponse = servletResponse;
}
}