自定义Interceptor中的NullPointerException

时间:2014-05-01 12:57:52

标签: java struts2

我是新的struts框架。我正在尝试创建自定义拦截器,我只是将给定的用户名转换为大写并在jsp中显示。

我的 index.jsp 代码为:

<s:form action="login"> <s:textfield name="name" label="UserName"></s:textfield> <s:submit value="Submit"></s:submit> </s:form>

拦截器代码是:

    public class CustomInterceptorExample implements Interceptor
{

    @Override
    public void destroy() 
    {
        // TODO Auto-generated method stub

    }

    @Override
    public void init() 
    {
        // TODO Auto-generated method stub
        System.out.println("Custom Interceptor called.....");
    }

    @Override
    public String intercept(ActionInvocation ai) throws Exception
    {
        // TODO Auto-generated method stub

        ValueStack vs=ai.getStack();
        String name=vs.findString("name"); //here i am getting exception
        System.out.println(name);
        vs.set("name", name.toUpperCase());
        System.out.println("intercept() called..."+ai.invoke());
        return ai.invoke();
    }

}

Struts.xml代码是:

<struts>
 <package name="default" extends="struts-default">

<interceptors>
<interceptor name="logerName" class="com.strutsLearner.CustomInterceptorExample"></interceptor>
</interceptors>    

<action name="product" class="com.strutsLearner.Product">
<result name="success">welcome.jsp</result>
</action>

<action name="login" class="com.strutsLearner.Login">
<interceptor-ref name="defaultStack"></interceptor-ref>  
<interceptor-ref name="logerName"></interceptor-ref>
<result>LogResult.jsp</result>  
</action>
</package>
</struts>    

堆栈跟踪是:

java.lang.NullPointerException
    com.strutsLearner.CustomInterceptorExample.intercept(CustomInterceptorExample.java:31)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488)
    org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)

谁能告诉我哪里弄错了。

1 个答案:

答案 0 :(得分:0)

您需要在 stuts.xml 文件中编写 defaultStack 拦截器

<interceptor-ref name="defaultStack"></interceptor-ref>