4

I have build a login snippet of code that is on the top of menu bar. If a user is in any of the page by navigating and presses all of sudden the login button, I'll like to see that person authenticated and at the same time stay on the page where he originally comes from. so I used this on the backing bean:

HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();

then if there is let say mypage.htm?a=2&b=2 get a=2&b=2 with the request.getQueryString()

but getQueryString returns null, how can I can have the original URL entirely from the backing bean?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
kefet
  • 721
  • 1
  • 12
  • 20

3 Answers3

5

It returned null because the command button does not submit to an URL which includes the query string. Look in the generated HTML output of <h:form>. You'll see that generated HTML <form action> does not include the query string at all.

You need to pass the current query string yourself as a request parameter in the login link/button.

Grab the current request URI and query string and add it as from parameter in login link/button (note: use a normal link/button, it doesn't need to be a command link/button):

<h:button value="login" outcome="/login">
    <f:param name="from" value="#{request.requestURI}#{empty request.queryString ? '' : '?'}#{request.queryString}" />
</h:button>

In login page, set the from parameter as view scoped bean property:

<f:metadata>
    <f:viewParam name="from" value="#{login.from}" />
</f:metadata>

In login action method, redirect to it:

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.
    }
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

<h:commandButton> sends a POST request to the server, more specifically to the Faces Servlet, and the JSF lifecycle starts. As you may know, you can't access to the query string parameters in a POST request.

In case you want to send a GET request from your form or retrieve the query string parameters when accessing to the page, you must map each expected query parameter using <f:viewParam>

<f:metadata>
    <f:viewParam id="a" name="a" value="#{bean.a}" />
    <f:viewParam id="b" name="b" value="#{bean.b}" />
</f:metadata>

More info:

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • Whilst `` is indeed part of the solution, I believe you misinterpreted the concrete problem. – BalusC Aug 22 '13 at 11:59
0

You can also solve this by changing the <h:form> wrapping the <h:commandButton> to an omnifaces form with includeRequestParams set to true: <o:form includeRequestParams="true">. See BalusC's response to this question.

Community
  • 1
  • 1
Etienne Dufresne
  • 401
  • 5
  • 11