在Acion中我们通常需要访问servlet的一些API,如request、session、application等。此时我们该怎么办呢?
方法1:使用ServletActionContext或ActionContext类。
//使用ServletActionContext
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = ServletActionContext.getRequest().getSession();
ServletContext application = ServletActionContext.getServletContext();
//---------------------------------------------------------------------------------
//使用ActionContext
Map<String, Object> session = ActionContext.getContext().getSession();
Map<String, Object> application = ActionContext.getContext.getApplication();
Map<String, Object> request = (Map<String, Object>)ActionContext.getContext().get("request");
Map<String, Object> session = (Map<String, Object>)ActionContext.getContext().get("session");
Map<String, Object> application = (Map<String, Object>)ActionContext.getContext().get("application");
方法2:使Action继承RequestAware、SessionAware、ApplicationAware三个接口(根据具体需要继承其中的某一个或某几个接口)。
public class ServletApiAction extends ActionSupport implements RequestAware, SessionAware, ApplicationAware
{
private Map<String, Object> request;
private Map<String, Object> session;
private Map<String, Object> application;
@Override
public String execute() throws Exception
{
return SUCCESS;
} @Override
public void setApplication(Map<String, Object> arg0)
{
this.application = arg0;
} @Override
public void setSession(Map<String, Object> arg0)
{
this.session = arg0;
} @Override
public void setRequest(Map<String, Object> arg0)
{
this.request = arg0;
}
}