Struts 2では、次の2つのメソッドを使用して
ServletContext
オブジェクトを取得できます。
1. ServletActionContext
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
インターフェースを実装するようにしてください。
Struts 2 ‘
servlet-config
‘インターセプタは、Actionクラスが
ServletContextAware
インタフェースを実装しているのを見て、
setServletContext()
メソッドを介してServletContext ** 参照を要求されたActionクラスに渡します。
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; } }
リファレンス
2 ServletContextAwareドキュメンテーション]