早期版本中可以如下操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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; } } |
如果报告
1 2 |
Caused by: java.lang.NullPointerException at org.apache.struts2.ServletActionContext.getServletContext(ServletActionContext.java:139) |
则代表这个版本的stucts2 中不支持这种写法,貌似2.3.16 版本的就不行,则可以通过实现ServletContextAware 接口来让spring拦截器来完成注入即可。
1 2 3 4 5 6 7 8 9 10 |
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; } } |