ServletActionContext.getServletContext()方法不是什么时候都能用的

1.当时我是这么建立这个类的

Java代码  收藏代码
  1. public class StaticAction extends ActionSupport { 
  2.     static
  3.         logDir = ServletActionContext.getServletContext().getRealPath("/"); //在这里打个断点 
  4.     } 
  5.  

2.在com.opensymphony.xwork2.DefaultActionInvocation 类下大约第362行

Java代码  收藏代码
  1. private void init() throws Exception { 
  2.         Map contextMap = createContextMap(); 
  3.  
  4.         createAction(contextMap); //在这个方法打个断点,该方法会去创建你所调用的Action。详情可以看看它里面的objectFactory.buildAction(proxy.getActionName(), proxy.getNamespace(), proxy.getConfig(), contextMap);这一句 
  5.  
  6.         if (pushAction) { 
  7.             stack.push(action); 
  8.         } 
  9.  
  10.         invocationContext = new ActionContext(contextMap); //注意你所调用的Action,它的ActionContext在这里才会创建。 
  11.         invocationContext.setName(proxy.getActionName()); 
  12.  
  13.         // get a new List so we don't get problems with the iterator if someone changes the list 
  14.         List interceptorList = new ArrayList(proxy.getConfig().getInterceptors()); 
  15.         interceptors = interceptorList.iterator(); 
  16.     } 

好了。调试运行。因为StaticAction有静态代码块,而objectFactory在创建action实例时,使用的是Class.forName(String cls)方式,它的具体实现如下:

Java代码  收藏代码
  1. java.lang.Class.java 
  2.  
  3.     public static Class<?> forName(String className)  
  4.                 throws ClassNotFoundException { 
  5.         return forName0(className, true, ClassLoader.getCallerClassLoader()); 
  6.     } 

看到forName0的第二个参数设置为true了吗?表示该类被JVM装载后,要不要立即初始化,如果设置成false,表示在将初始化的工作推迟到了newInstance的时候进行.所以,当方法createAction(contextMap)被调用时,要执行的StaticAction的静态代码块肯定会被调用的。


当运行到ServletActionContext.getServletContext().getRealPath("/")这一句时,继续查看ServletActionContext.getServletContext()的来源:


org.apache.struts2.ServletActionContext.java 大概第137行

Java代码  收藏代码
  1. public static ServletContext getServletContext() { 
  2.     return (ServletContext) ActionContext.getContext().get(SERVLET_CONTEXT); 

可以看到其实调用的是ActionContext.getContext().get(SERVLET_CONTEXT);过来的,而咱们在最开始也看到了createAction(contextMap);方法在 invocationContext = new ActionContext(contextMap); 方法执行之前,是无法正常得到SERVLET_CONTEXT的,所以,就会出空指针异常了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值