一种方法是利用工具类ActionContext,ServletActionContext
另一种是通过实现Action接口,利用接口约定的方法注入.(推荐),下面是这种方案的示例
package utils;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.util.ServletContextAware;
/***
* Action如何使用request,session,application:
* 要Action实现以下Aware接口,利用接口约定的方法注入.(推荐)
* 原因:减少了Struts2框架API对Action类的侵入,提高Action的灵活性.
* RequestAware、SessionAware、ApplicationAware、ServletRequestAware、ServletContextAware
* @author huawei
*
*/
public class BaseAction implements RequestAware,SessionAware,ApplicationAware,
ServletRequestAware,ServletContextAware{
public Map<String, Object> request;
public Map<String, Object> session;
public Map<String, Object> application;
public HttpServletRequest httpRequest;
public HttpSession httpSession;
public ServletContext httpApplication;
@Override
public void setServletContext(ServletContext httpApplication) {
this.httpApplication = httpApplication;
}
@Override
public void setServletRequest(HttpServletRequest httpRequest) {
this.httpRequest = httpRequest;
this.httpSession = httpRequest.getSession();
}
@Override
public void setApplication(Map<String, Object> application) {
this.application = application;
}
@Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
@Override
public void setRequest(Map<String, Object> request) {
this.request = request;
}
}