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;
}
}
參考
-
Struts 2 ServletContextAware文件