在Struts 2中,可以使用以下两种方法来获取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接口。
当Struts 2'servlet-config '拦截器看到ServletContextAware接口实现了Action类时,它将通过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;
}
}
参考
翻译自: https://mkyong.com/struts2/how-to-get-the-servletcontext-in-struts-2/