异常信息如下:
java.lang.NullPointerException
day9_11.login.web.LoginAction.login(LoginAction.java:15)
java.base / jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(本机方法)
java.base / jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
java.base / jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.base / java.lang.reflect.Method.invoke(Method.java:564)
com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:453)
com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:292)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:255)
day9_11.login.interceptor.MyInterceptor.intercept(MyInterceptor.java:29)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:511)
org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
出现异常的原因是在struts.xml中配置action拦截器时,将默认拦截器栈覆盖了,最终只有自定义拦截器生效,从而导致user没有被注入,出现空指针异常。原配置如下:
<interceptors>
<interceptor name="loginInterceptor" class="day9_11.login.interceptor.MyInterceptor"></interceptor>
</interceptors>
<action name="user_*" class="day9_11.login.web.LoginAction" method="{1}">
<interceptor-ref name="loginInterceptor"></interceptor-ref>
<result>/WEB-INF/jsp/index.jsp</result>
<result name="error">/error.jsp</result>
<result name="login">/login.jsp</result>
</action>
修改后的配置如下:
<interceptors>
<interceptor name="loginInterceptor" class="day9_11.login.interceptor.MyInterceptor"></interceptor>
<interceptor-stack name="myInterceptor">
<interceptor-ref name="loginInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<action name="user_*" class="day9_11.login.web.LoginAction" method="{1}">
<interceptor-ref name="myInterceptor"></interceptor-ref>
<result>/WEB-INF/jsp/index.jsp</result>
<result name="error">/error.jsp</result>
<result name="login">/login.jsp</result>
</action>
修改后,action对象中的属性可以被默认拦截器栈中的拦截器进行注入,从而解决了空指针的问题。