How To Get The ServletContext In Struts 2

早期版本中可以如下操作

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;

	}

}

如果报告

Caused by: java.lang.NullPointerException
    at org.apache.struts2.ServletActionContext.getServletContext(ServletActionContext.java:139)

则代表这个版本的stucts2 中不支持这种写法,貌似2.3.16 版本的就不行,则可以通过实现ServletContextAware 接口来让spring拦截器来完成注入即可。

import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class CustomerAction extends ActionSupport implements ServletContextAware{
	private ServletContext context;
	public void setServletContext(ServletContext context) {
		this.context = context;	
	}
}

发布者