关于Java:当我为登录用户创建会话时,如何在struts2中维护hibernate会话?

 2021-04-26 

How to maintain the hibernate session in struts2, when I created session for login user?

我做了一个应用程序,因为我应该维护一个登录用户会话,所以我创建了一个登录Interceptor来维护它。我继承了做hibernate会话的目的。当我将登录拦截器与" hibernate-default "一起使用时,会引发Nullpointer异常。此处的hibernate会话显示为NULL。如何维护hibernate会话。

下面是我的struts.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 <package name="helloworld" extends="hibernate-default">
    <interceptors>
        <interceptor name="mylogging" class="Demo.AuthenticationInterceptor"></interceptor>
        <interceptor-stack name="loggingStack">
            <interceptor-ref name="mylogging" />
            <interceptor-ref name="defaultStack" />                
        </interceptor-stack>
    </interceptors>
    <default-interceptor-ref name="loggingStack"></default-interceptor-ref>
   
        <result name="input">/login.jsp</result>
        <result name="success" type="redirect">/list.jsp</result>
        <result name="failure">/error.jsp</result>
    </action>
     
        <interceptor-ref name="basicStackHibernate"/>          
        <result name="success">/register1.jsp</result>
        <result name="login">/login.jsp</result>
    </action>
 </package>
</struts>

我用于维护每个动作的会话,但我的会话显示为NULL。

我的AuthenticationInterceptor.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class AuthenticationInterceptor implements Interceptor
{
  public String intercept(ActionInvocation ai) throws Exception
 {
    System.out.println("inside the interceptor()......new");
    Map session1 = ai.getInvocationContext().getSession();
    String name = (String) session1.get("name");
    System.out.println("inside the session or loginaction=" + name);
    if ((session1.get("name") != null) || (session1.get("name") == null))
   {
        System.out.println("inside the session or loginaction");
        return ai.invoke();
    } else {
        return"login";
    }
}
}

例外是:

1
2
3
4
5
6
7
8
9
10
11
12
Session =null
java.lang.NullPointerException
at Demo.UserDAOImpl.listUser(UserDAOImpl.java:57)
at Demo.UserAction.list(UserAction.java:53)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at   sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
null
at java.lang.reflect.Method.invoke(Method.java:606)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:440)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:279)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)


使用basicStackHibernate拦截器是因为要执行List,Edit和Delete操作以进行Hibernate访问(会话和/或事务)。

1
<interceptor-ref name="defaultStackHibernate" />