我的问题是为什么我会收到NullPointerException,尤其是在可变会话中,控制台日志是:
Grave: java.lang.NullPointerException
at com.curso.struts2.dao.UserDAOImpl.listUser(UserDAOImpl.java:28)
at com.curso.struts2.UserAction.list(UserAction.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
...
我的源代码是:
web.xml
<listener>
<listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>
</listener>
<context-param>
<param-name>tilesDefinitions</param-name>
<param-value>/WEB-INF/tiles.xml</param-value>
</context-param>
struts.xml
<struts>
<constant name="struts.devMode" value="false" />
<constant name="struts.custom.i18n.resources" value="ApplicationResources" />
<package name="default" extends="hibernate-default,struts-default" namespace="/">
<result-types>
<result-type name="tiles"
class="org.apache.struts2.views.tiles.TilesResult" />
</result-types>
<action name="addUser" method="add" class="com.curso.struts2.UserAction">
<result name="success" type="redirect">listUser</result>
</action>
<action name="listUser" method="list" class="com.curso.struts2.UserAction">
<result name="success">register.tiles</result>
</action>
</package>
UserDAOImpl.java
@SuppressWarnings("unchecked")
@Override
public List<User> listUser() {
List<User> courses = null;
try {
System.out.println("UserDAOImpl.listUser()_session:" + session);
Query query = session.createQuery("from User");
courses = query.list();
} catch (Exception e) {
e.printStackTrace();
}
return courses;
}
在这种情况下, session 变量显示为空
tiles.xml
<definition name="/register.tiles" extends="baseLayout">
<put-attribute name="title" value="Struts 2 Hibernate example"/>
<put-attribute name="body" value="/jsp/register.jsp"></put-attribute>
</definition>
在我的register.jsp中,我发送一张表格