命中 bean 方法并重定向 GET 请求 [英] Hit a bean method and redirect on a GET request

查看:20
本文介绍了命中 bean 方法并重定向 GET 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 GlassFish 上使用 JSF 2 和 PrimeFaces 2.1.

I'm using JSF 2 and PrimeFaces 2.1 on GlassFish.

我有一个页面,旨在让人们在遵循回调 URL 后执行操作(例如作为嵌入在电子邮件中的链接或作为某些外部身份验证或支付服务的回调 URL 参数).就我而言,我需要重置密码.回调 URL 有一个 token GET 参数,如下所示:

I have a page that is intended to allow people to perform an action after following a callback URL (e.g. as link embedded in email or as callback URL parameter of some external authentication or payment service). In my case I need to reset the password. The callback URL has a token GET parameter like so:

http://example.com/app/resetPasswordForm.jsf?token=abc123

resetPasswordForm.jsf 的页面加载时,我需要检查令牌是否有效,如果无效则重定向到主应用程序屏幕.

On page load of resetPasswordForm.jsf, I need to check if the token is valid and redirect to the main app screen if it's not valid.

我的想法是有一个bean方法,如:

My thinking is to have a bean method like:

public String resetPasswordHandler.showResetForm(String token) {
  if /* token is valid */ {
    return "resetPasswordForm.jsf";
  } else {
    return "main.jsf";
  }
}

但是我怎么会导致该方法在页面加载时被点击?

But how would I cause that method to get hit on page load?

不确定如何进行 - 欢迎提出建议.

Not sure how to proceed -- suggestions are welcome.

推荐答案

使用 在呈现视图之前触发 bean 方法并简单地返回导航结果(这将隐式为视为重定向).

Use <f:viewAction> to trigger a bean method before rendering of the view and simply return a navigation outcome (which will implicitly be treated as a redirect).

例如

<f:metadata>
    <f:viewParam name="token" value="#{authenticator.token}" />
    <f:viewAction action="#{authenticator.check}" />
</f:metadata>

@ManagedBean
@RequestScoped
public class Authenticator {

    private String token;

    public String check() {
        return isValid(token) ? null : "main.jsf";
    }

    // Getter/setter.
}

如果您还没有使用 JSF 2.2,那么您可以使用 ExternalContext#redirect().

If you're not on JSF 2.2 yet, then you can use the <f:event type="preRenderView"> workaround in combination with ExternalContext#redirect().

<f:metadata>
    <f:viewParam name="token" value="#{authenticator.token}" />
    <f:event type="preRenderView" listener="#{authenticator.check}" />
</f:metadata>

@ManagedBean
@RequestScoped
public class Authenticator {

    private String token;

    public void check() throws IOException {
        if (!isValid(token)) {
            FacesContext.getCurrentInstance().getExternalContext().redirect("main.jsf");
        }
    }

    // Getter/setter.
}

另见:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆