下面是网络流行的两种方式,推荐使用IOC这种。
package com.alpha.test; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.ServletResponseAware; import org.apache.struts2.interceptor.SessionAware; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class BaseAction extends ActionSupport implements SessionAware, ServletRequestAware, ServletResponseAware { private static final long serialVersionUID = 1L; // not IOC ActionContext context = ActionContext.getContext(); HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST); HttpServletResponse response = (HttpServletResponse) context.get(ServletActionContext.HTTP_RESPONSE); @SuppressWarnings("unchecked") Map session = context.getSession(); //Map session = (Map) context.get(ActionContext.SESSION); // IOC @SuppressWarnings("unchecked") public void setSession(Map session) { this.session = session; } public void setServletRequest(HttpServletRequest request) { this.request = request; } public void setServletResponse(HttpServletResponse response) { this.response = response; } }