2

I use the following web.xml setting to direct unlogged-in user to /faces/loginPage.xhtml.
In /faces/loginPage.xhtml I will authenticate the user and redirect the user to the home page.

Now I want to redirect the user to the page she initially requested, instead of the home page. How do I do that? Specifically, how to get the url of the initially requested page?

<security-constraint>
    <display-name>MyConstraint</display-name>
    <web-resource-collection>
        <web-resource-name>wrcoll</web-resource-name>
        <description />
        <url-pattern>/faces/secured/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <description />
        <role-name>myUser</role-name>
    </auth-constraint>
</security-constraint>

<login-config>
    <auth-method>FORM</auth-method>
    <realm-name>my_ldap_domain</realm-name>
    <form-login-config>
        <form-login-page>/faces/loginPage.xhtml</form-login-page>
        <form-error-page>/error.xhtml</form-error-page>
    </form-login-config>
</login-config>
BalusC
  • 1,040,783
  • 362
  • 3,548
  • 3,513
Ran Tang
  • 231
  • 5
  • 11
  • A detailed answer is here [http://stackoverflow.com/questions/8024344/user-login-with-jsf-2-0/39379256#39379256](http://stackoverflow.com/questions/8024344/user-login-with-jsf-2-0/39379256#39379256) – Tunde Michael Sep 07 '16 at 21:34

1 Answers1

2

You seem to be performing the login through a JSF managed bean instead of through j_security_check. Because if you were using the latter, this is already automatically taken into account.

The FORM based authentication login page is been displayed by a RequestDispatcher#forward() the usual Servlet API way. So the request URI of the initially requested page is available as a request attribute with the name as specified by RequestDispatcher.FORWARD_REQUEST_URI, which has a value of "javax.servlet.forward.request_uri".

So, in EL context it's available as

#{requestScope['javax.servlet.forward.request_uri']}

And in JSF context it's available as

String originalURL = (String) FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get("javax.servlet.forward.request_uri");

This needs to be collected on the initial request, not on the form submit. Easiest would be to grab it in the constructor of a @ViewScoped managed bean which is attached to the page. An alternative with a @RequestScoped bean is to enclose a plain HTML <input type="hidden"> in with that value in the login form and set it as @ManagedProperty.

BalusC
  • 1,040,783
  • 362
  • 3,548
  • 3,513