Interceptor无法访问Action Parameters

时间:2013-07-15 08:49:02

标签: java java-ee struts2 interceptor valuestack

我正在为struts2拦截器创建一个示例。我创建了一个简单的登录页面,并使用自定义拦截器类来加密输入。但拦截器正在将ValueStack的输入值读作null

我不明白我做错了什么。我想struts.xml和拦截器类就足够了。如果您需要更多我的代码,请告诉我们。

struts.xml中

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <constant name="struts.devMode" value="true" />
    <package name="myPackage" extends="struts-default">
    <interceptors>
            <interceptor name="encrypt" class="com.keyur.struts2.interceptors.EncryptDecryptInterceptor"/>
        </interceptors>
        <action name="validatorAction" class="com.keyur.struts2.ActionClasses.validatorClass" method="execute">
        <interceptor-ref name="encrypt"></interceptor-ref>
        <result name="success">/success.jsp</result>
        <result name="input">/index.jsp</result>
        </action>
    </package>
</struts>

拦截器.java文件

package com.keyur.struts2.interceptors;

import com.keyur.struts2.ActionClasses.validatorClass;
import com.keyur.struts2.beans.EncryptorDecryptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.opensymphony.xwork2.util.ValueStack;

public class EncryptDecryptInterceptor implements Interceptor {

        EncryptorDecryptor encdec = new EncryptorDecryptor();

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

    }

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

    }

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

        String result = arg0.invoke();

        ValueStack stack = arg0.getStack();
        String username = stack.findString("username");
        String password = stack.findString("password");

        System.out.println("Username: "+((validatorClass)stack.peek()).getUsername());
        System.out.println("Password: "+((validatorClass)stack.peek()).getPassword());
        //System.out.println(username);
        //System.out.println(password);

        //stack.set("username", encdec.encryptText(username));
        //stack.set("password", encdec.encryptText(password));

        return result;
    }
}

EncryptorDecryptor是我定义的一个单独的类,它可以自行运行。

1 个答案:

答案 0 :(得分:3)

如果要访问参数,params拦截器应该先行

<action name="validatorAction" class="com.keyur.struts2.ActionClasses.validatorClass" method="execute">
   <interceptor-ref name="params"></interceptor-ref>
   <interceptor-ref name="encrypt"></interceptor-ref>
   <interceptor-ref name="defaultStack"></interceptor-ref>
   <result name="success">/success.jsp</result>
   <result name="input">/index.jsp</result>
</action>

您的问题是这些参数没有转到valueStack,您应该从动作上下文中获取它们。

Map params = ActionContext.getContext().getParameters();

但在params拦截器后,他们应该在那里。