FabIO FabIO - 1 year ago 55
Java Question

User login with JSF 2.0

I am trying - with JSF 2.0 - to implement in a neat way the login/remember me/logout management. Since the traditional

<form action="j_security_check" ...
way lacks of flexibility I decided to follow a different path, but I found a problem.

Declarative security is properly set both in the application server through
and in web.xml through

The login page:

<h:form id="loginForm">
<h:panelGrid columns="2" cellspacing="5">
<h:outputText value="Username" />
<h:inputText value="#{loginBean.username}" />
<h:outputText value="Password:" />
<h:inputText value="#{loginBean.password}" />
<h:outputLabel value=""/>
<h:commandButton value="Login" action="#{loginBean.login}" />

And the simple LoginBean#login():

public String login( )
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance( ).getExternalContext( ).getRequest( );
try {
request.login( username, password );
catch ( ServletException e ) {
FacesContext.getCurrentInstance().addMessage( "Unknown login...
return null;
return "i_dont_know_where_you_were_going";

Everything works fine, but after a successful login I don't know how to forward the user to its original request. Since the login page is automatically interposed between the client request and "any" secured resource I need a way to understand where to redirect the action.
request.getRequestURL( )
doesn't help, probably because of a
(which overwrites the request url) intervention. Do you think this is an appropriate way to manage the login process? If so, any hint about the problem?

Thanks a lot!

Answer Source

Add something like the following line to your login view. It stores the requested page during the login.

<f:param name="redirect" value="#{requestScope['javax.servlet.forward.request_uri']}" />

Then get the requested uri in your login bean.

FacesContext context = FacesContext.getCurrentInstance();
String redirect = context.getExternalContext().getRequestParameterMap().get("redirect");

Add ?faces-redirect=true to the string and return it.