How To Get The ServletContext In Struts 2
In Struts 2 , you can use the following two methods to get the ServletContext object.
1. ServletContextAware
Make your class implements the org.apache.struts2.util.ServletContextAware interface.
** UPDATE: Struts 2 Complete tutorial now available here.
When Struts 2 “servlet-config” interceptor is seeing that an Action class is implemented the ServletContextAware interface, it will pass a ServletContext reference to the requested Action class via the setServletContext()method.
package com.simplecode.action;
import javax.servlet.ServletContext;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.Action;
public class ContextAction implements ServletContextAware,Action {
ServletContext context;
public String execute() throws Exception
{
return SUCCESS;
}
public void setServletContext(ServletContext context)
{
this.context = context;
}
}
2. ServletActionContext
Get the ServletContext object directly from org.apache.struts2.ServletActionContext
package com.simplecode.action;
import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.Action;
public class ContextAction implements Action
{
public String execute() throws Exception
{
ServletContext context = ServletActionContext.getServletContext();
return SUCCESS;
}
}