今天写一个EntityAction,其中有一个功能是获取EntityManager,想来想去觉得直接从applicationContext中获取最方便 免去了自己写setter方法,想好了就来实施啦
public class WebworkEntityAction<E, ID extends Serializable, M extends GenericDao<E, ID>>
extends WebworkActionSupport implements InitializingBean{
protected E entity;
protected ID id;
protected M entityManager;
/**
* 保存实体
*/
protected String save(){
entityManager.save(entity);
return LIST;
}
public void afterPropertiesSet(){
//初始化entityManager
Class managerClass = GenericsUtils.getSuperClassGenricType(getClass(), 2);
//ServletContext sc = this.getSession().getServletContext();
WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
Assert.isTrue(managerClass instanceof Class, "变量managerClass不是Class的实例");
Map beans = context.getBeansOfType(managerClass);
Assert.isTrue(beans != null && beans.size() > 0, "找不到这种类型的bean:" + managerClass.getName());
String beanName = (String)beans.keySet().iterator().next();
entityManager = (M)context.getBean(beanName);
}
public ServletContext getServletContext(){
return ServletActionContext.getServletContext();
}
写罢 运行 testSave() 报告空指针异常 在getServletContext()在这句上
脑子一片空白,焦点集中到getServletContext()方法中 搞了半天没理出个头绪
稍作休息 重新整理逻辑
action初始化步骤如下
1.在spring context中执行构造函数
2.在spring context中执行InitializingBean.afterPropertiesSet()方法(实例初始化结束)
3.经过一系列的拦截器。包括向ActionContext中写入request数据
ok问题的根源已经找到了
我们在afterPropertiesSet中执行了getServletContext()而这时拦截器还没向ActionContext写数据 难怪报空指针异常
这个问题到此结束
另外还有一个问题,
ServletActionContext.getReqest();
方法返回的却不是null,而
ServletActionContext.getReqest().getSession()
;又是null
其实可以作为两类事件来看
request 客户端来的数据
sesssion、 servletcontext 服务端数据