0

I have this login form:

<h:form>
    <h:panelGrid columns="2" >
        <h:outputLabel for="username" value="Login:"/>
        <h:inputText id="username" value="#{userController.userName}" required="true"/>
        <h:outputLabel for="password" value="#{msg.password}"/>
        <h:inputSecret id="password" value="#{userController.password}" required="true"/>
        <h:column/>
        <h:commandButton value="#{msg.login}" action="#{userController.login}"/> 
        </h:panelGrid>
</h:form>

With this backing bean:

@ManagedBean(name = "userController")
@SessionScoped
public class UserController {
  private String userName = "";
  private String password = "";

  //getter, setters

  public String login(){
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
    try {
        request.login(userName, password);
    } catch (ServletException e) {
    }            

    return "next-page.xhtml"; //if login processes is proper, i redirect to next page 
   }
}

I read in Best practices in JSF: model, actions, getters, navigation, phaselisteners that

I always post back to the same view (return null or void and then render/include the result conditionally. For page-to-page navigation I don't use POST requests (for which navigation cases are mandatory) simply because that's plain bad for UX (User eXperience; browser back button doesn't behave as it should and URL's in browser address bar are always one step behind because it are by default forwards, not redirects) and SEO (Search Engine Optimization; searchbots doesn't index POST requests). I just use outputlinks or even plain HTML elements for page-to-page navigation.

So, what should I do when my login is proper and I want to immediately redirect to next-page.xhtml?

Community
  • 1
  • 1
kuba44
  • 1,838
  • 9
  • 34
  • 62
  • Make use of an "if else" statement to condionnally `return` the appropriate navigation case outcome. – Omar Nov 11 '13 at 11:56

1 Answers1

1

In the end of the try, perform the navigation with ?faces-redirect=true so that a redirect is performed. In the catch, return null so that it stays in the same page.

try {
    request.login(userName, password);
    return "next-page.xhtml?faces-redirect=true";
} catch (ServletException e) {
    context.addMessage(null, new FacesMessage("Unknown login"));
    return null;
}            

For the sake of completeness, I added a faces message on login failure, otherwise the enduser would have no clue why the page seemingly reloads itself without any form of feedback. This message will be shown in a <h:messages globalOnly="true">.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555