Struts2 RequestAware接口的使用

时间:2013-01-28 22:32:06

标签: struts2

如果我的行动类如下:

<!-- language: lang-java -->

package org.tutorial.struts2.action;
import java.util.Map;
import org.apache.struts2.interceptor.RequestAware;
import org.tutorial.struts2.service.TutorialFinder;
import com.opensymphony.xwork2.Action;

public class TutorialAction implements Action, RequestAware {
    private String language;
    private String bestTutorialSite;

    public String execute() {
        System.out.println(language);
        setBestTutorialSite(new TutorialFinder().getBestTutorialSite(language));
        System.out.println(bestTutorialSite);       
        if (getBestTutorialSite().contains("Java"))
            return SUCCESS;
        else
        return ERROR;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }

    public String getBestTutorialSite() {
        return bestTutorialSite;
    }

    public void setBestTutorialSite(String bestTutorialSite) {
        this.bestTutorialSite = bestTutorialSite;
    }

    @Override
    public void setRequest(Map<String, Object> requestObj) {
        System.out.println(bestTutorialSite);
        requestObj.put("message", bestTutorialSite);
    }

}

在execute方法之前调用此操作时,Struts2框架已经填充了该语言。在execute方法中,setBestTutorialSite方法用于填充私有字段bestTutorialSite

现在我想到将这个私有字段bestTutorialSite设置到请求属性中(在setRequest方法中)。但是我注意到在填充任何私有字段(如语言)之前首先调用此方法。因此,在setRequest方法中,bestTutorialSite的系统打印始终为空。

我认为在调用JSP页面之前,我能够使用bestTutorialSite(从execute方法中捕获)设置此属性。

我不认为我完全掌握了对Struts2流程的理解 - 显然! :OP

请帮忙。 感谢。

2 个答案:

答案 0 :(得分:1)

我假设您正在使用 defaultStack ,如下所示:

<interceptor-stack name="defaultStack">
    <interceptor-ref name="exception"/>
    <interceptor-ref name="alias"/>
    <interceptor-ref name="servletConfig"/>
    <interceptor-ref name="prepare"/>
    <interceptor-ref name="i18n"/>
    <interceptor-ref name="chain"/>
    <interceptor-ref name="debugging"/>
    <interceptor-ref name="profiling"/>
    <interceptor-ref name="scopedModelDriven"/>
    <interceptor-ref name="modelDriven"/>
    <interceptor-ref name="fileUpload"/>
    <interceptor-ref name="checkbox"/>
    <interceptor-ref name="staticParams"/>
    <interceptor-ref name="params">
        <param name="excludeParams">dojo\..*</param>
    </interceptor-ref>
    <interceptor-ref name="conversionError"/>
    <interceptor-ref name="validation">
        <param name="excludeMethods">input,back,cancel,browse</param>
    </interceptor-ref>
    <interceptor-ref name="workflow">
        <param name="excludeMethods">input,back,cancel,browse</param>
    </interceptor-ref>
 </interceptor-stack>

如您所见, servletConfig 拦截器位于 params 拦截器之前,这意味着将在您的操作上设置第一个Request(使用 servletConfig )并且然后您的操作将填充请求参数(使用 params )。

你想要达到的目的是改变拦截器的顺序,当它以错误的方式使用时可能会有害。

答案 1 :(得分:0)

我认为请求拦截器将首先执行,之后执行execute()方法。 这可能是问题所在。