为什么getQueryString()在使用h:commandButton的jsf支持bean中不起作用

kef*_*fet 4 jsf jsf-2

我已经构建了一个位于菜单栏顶部的登录代码片段.如果用户在任何页面中通过导航并突然按下登录按钮,我会希望看到该人员经过身份验证并同时停留在他最初来自的页面上.所以我在支持bean上使用了这个:

HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
Run Code Online (Sandbox Code Playgroud)

然后如果有说mypage.htm?a = 2&b = 2使用request.getQueryString()得到a = 2&b = 2

但getQueryString返回null,我怎样才能完全从支持bean获得原始URL?

Bal*_*usC 5

它返回null是因为命令按钮没有提交到包含查询字符串的URL.查看生成的HTML输出<h:form>.您将看到生成的HTML <form action>根本不包含查询字符串.

您需要自己将当前查询字符串作为请求参数传递到登录链接/按钮中.

抓取当前请求URI和查询字符串,并将其作为from参数添加到登录链接/按钮中(注意:使用普通链接/按钮,它不需要是命令链接/按钮):

<h:button value="login" outcome="/login">
    <f:param name="from" value="#{request.requestURI}#{empty request.queryString ? '' : '?'}#{request.queryString}" />
</h:button>
Run Code Online (Sandbox Code Playgroud)

在登录页面中,将from参数设置为视图范围的bean属性:

<f:metadata>
    <f:viewParam name="from" value="#{login.from}" />
</f:metadata>
Run Code Online (Sandbox Code Playgroud)

在登录操作方法中,重定向到它:

public void submit() throws IOException {
    User user = userService.find(username, password);

    if (user != null) {
        // ... Do your login thing.

        FacesContext.getCurrentInstance().getExternalContext().redirect(from);
    } else {
        // ... Do your "unknown login" thing.
    }
}
Run Code Online (Sandbox Code Playgroud)