今天使用Struts2的時候遇到一個怪異的問題,首先在struts.xml中配置的action是沒有問題的,Java類也寫好了。但是運行的時候報
告如下錯誤:
javax.servlet.ServletException: Unable to instantiate Action,
cn.edu.cup.actions.JobManager, defined for 'jobList' in namespace
'/'null - action -
file:/K:/Softwares/%E6%95%99%E5%AD%A6%E7%9B%B8%E5%85%B3
經過網上仔細搜索發現,根本原因在于我在方法中使用了 Student s = (Student) session.getAttribute("user");
其中session是在構造函數中獲取的。但是,通過分析Struts的原理(參見http://t8500071.javaeye.com/blog
/348057),由于Action先于ActionContext對象實例之前創建,所以session對象是null,因此,會報告空指針錯誤!
明白了上述原理后,將獲取session的語句從構造函數中刪除,放到方法中,程序終于正常了!