如何獲取ServletContext對象

在Struts2中,可以使用以下兩種方法來獲取ServletContext對象。

1. ServletActionContext

直接從 org.apache.struts2.ServletActionContext 獲取 ServletContext 對象。
import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class CustomerAction extends ActionSupport{

	public String execute() throws Exception {

		ServletContext context = ServletActionContext.getServletContext();

		return SUCCESS;

	}

}

2. ServletContextAware

讓你的類實現了org.apache.struts2.util.ServletContextAware介面。
當Struts2 的 “servlet-config”攔截器是看到了一個Action類實現ServletContextAwareinterface,它會通過一個ServletContext引用Action類通過setServletContext()方法請求。
import javax.servlet.ServletContext;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.ActionSupport;

public class CustomerAction
    extends ActionSupport implements ServletContextAware{

	ServletContext context;

	public String execute() throws Exception {

		return SUCCESS;

	}

	public void setServletContext(ServletContext context) {
		this.context = context;
	}
}

參考

  1. Struts 2 ServletContextAware文檔

上一篇: Struts2獲取HttpServletResponse實例 下一篇: Struts2配置Action類的靜態參數