I am trying to use an Interceptor
to restrict users from performing certain actions.
ContainsKeyInterceptor
:
public class ContainsKeyInterceptor extends AbstractInterceptor implements SessionAware {
private static final long serialVersionUID = 1L;
private Map<String, Object> session;
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
if(session == null) {
System.out.println("session is null");
}
if(session.containsKey("currentId")) {
return "index";
}
String result = actionInvocation.invoke();
return result;
}
@Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
}
It is supposed to redirect the user to the index page if currentId
is found in the session
.
However, I am getting a NullPointerException
, saying session
is null, as verified by the if-check.
struts.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.devMode" value="false" />
<!-- actions available to guests -->
<package name="guest" extends="struts-default">
<interceptors>
<interceptor name="containskeyinterceptor" class="com.mypackage.interceptor.ContainsKeyInterceptor" />
</interceptors>
<action name="index" class="com.mypackage.action.IndexAction">
<interceptor-ref name="containskeyinterceptor" />
<result type="redirect">/index.jsp</result>
<result name="index" type="redirect">/index.jsp</result>
</action>
<action name="login" class="com.mypackage.action.LoginAction">
<interceptor-ref name="containskeyinterceptor" />
<result type="redirect">/index.jsp</result>
<result name="input">/login.jsp</result>
<result name="index" type="redirect">/index.jsp</result>
</action>
</package>
<!-- actions available to members -->
<package name="member" extends="struts-default">
<action name="logout" class="com.mypackage.action.LogoutAction">
<result type="redirectAction">
<param name="actionName">index</param>
</result>
</action>
</package>
</struts>
Why is the session
null and how to resolve?
(This was the reference I used.)