JSF 2 and Post/Redirect/Get?

22
如果我理解错误,请纠正我,但我认为所有非AJAX提交都应该使用Post/Redirect/Get(PRG)方式,因为GET应该用于刷新/查询数据,在我的情况下,我所能想到的应用程序页面实际上只是更新数据然后刷新页面,所以我认为PRG很适合这里。
我相信我可以使用faces-config.方式来做到这一点,在那里我可以利用,或者我可以使用return "myview.xhtml?faces-redirect=true"。
现在的问题是...
是否有任何方法可以全局配置这个,使得对于非AJAX调用/提交,自动使用faces-redirect=true,使得我的源代码像这样简单:
return "myview";

@romaintaz:谢谢,忘记引用重定向标签了,哈哈。 - Bertie
1个回答

28

你可以使用自定义的ConfigurableNavigationHandler来完成这个操作。这是一个开始的例子:

package com.example;

import java.util.Map;
import java.util.Set;

import javax.faces.application.ConfigurableNavigationHandler;
import javax.faces.application.NavigationCase;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;

public class RedirectNavigationHandler extends ConfigurableNavigationHandler {

    private NavigationHandler parent;

    public RedirectNavigationHandler(NavigationHandler parent) {
        this.parent = parent;
    }

    @Override
    public void handleNavigation(FacesContext context, String from, String outcome) {
        if (!outcome.endsWith("?faces-redirect=true")) {
            outcome += "?faces-redirect=true";
        }

        parent.handleNavigation(context, from, outcome);        
    }

    @Override
    public NavigationCase getNavigationCase(FacesContext context, String fromAction, String outcome) {
        if (parent instanceof ConfigurableNavigationHandler) {
            return ((ConfigurableNavigationHandler) parent).getNavigationCase(context, fromAction, outcome);
        } else {
            return null;
        }
    }

    @Override
    public Map<String, Set<NavigationCase>> getNavigationCases() {
        if (parent instanceof ConfigurableNavigationHandler) {
            return ((ConfigurableNavigationHandler) parent).getNavigationCases();
        } else {
            return null;
        }
    }

}

faces-config.xml中如下注册:

<application>
    <navigation-handler>com.example.RedirectNavigationHandler</navigation-handler>
</application>  

当action方法返回void(停留在相同页面)时,是否可以使此处理程序起作用:<h:commandButton action =“#{bean.voidMethod}”/>? - marioosh
2
嗨,阿尔伯特。您可以将代码添加到处理程序中,并检查请求是否为AJAX请求,从FaceContext获取PartialViewContext,然后调用PartialViewContext.isAJAXRequest http://download.oracle.com/javaee/6/api/javax/faces/context/PartialViewContext.html#isAjaxRequest%28%29。 - victor herrera
嗨,BalusC:您为什么要extends ConfigurableNavigationHandler而不是extends NavigationHandlerConfigurableNavigationHandlerNavigationHandler提供了什么更多的功能? - Thang Pham
这个能在Faces Flow应用中应用吗?问题是outcome可能是FlowNode的名称,那么它将不会产生任何效果(重定向将在稍后从outcome中剥离)。 - T.G
有没有一个好的方法可以在重定向后保持RequestScoped bean的状态? - mattalxndr
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接