Action直接访问Servlet API

1.ActionContext

import com.opensymphony.xwork2.ActionContext;

...

ActionContext ctx = ActionContext.getContext();
...

//操作session
ctx.getSession().put("key:xxx", "value:xxx");

//操作application
ctx.getApplication().put("key:xxx", "value:xxx");

2.一些重要接口

虽然Struts2提供了ActionContext来操作ServletAPI,但是这种访问

毕竟不能获得ServletAPI实例。

Action如果实现了以下接口,便可访问Servlet对象。

ServletContextAware-ServletContext

ServletRequestAware-HttpServletRequest

ServletResponseAware-HttpServletResponse

eg:

import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
...

public class SharpAction implements ServletRequestAware {
  ...
  
  //给Action配上需要的servlet类属性
  private HttpServletRequest request;

  //这个是接口的方法,必须要实现
  public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

  public String execute() throws Exception {
	  ...  
	    request.setAttribute("key:xxx", "value:xxx");
    ...
}

相关推荐