根据登录是否成功有条件地导航

时间:2013-11-11 11:44:01

标签: jsf post jsf-2 login navigation

我有这个登录表单:

<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>

使用这个支持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 
   }
}

我在Best practices in JSF: model, actions, getters, navigation, phaselisteners读到了

  

我总是回发到同一个视图(返回null或void,然后有条件地渲染/包含结果。对于页面到页面的导航,我不使用POST请求(导航情况是强制性的),因为那是对用户体验不利(用户体验;浏览器后退按钮的行为不应该如此,浏览器地址栏中的URL总是落后一步,因为它是默认转发,而不是重定向)和SEO(搜索引擎优化;搜索引擎优化; index POST请求。)我只使用outputlinks甚至纯HTML元素进行页面到页面的导航。

那么,当我的登录正确并且我想立即重定向到next-page.xhtml时,我该怎么办?

1 个答案:

答案 0 :(得分:1)

try的末尾,使用?faces-redirect=true执行导航,以便执行重定向。在catch中,返回null,使其保持在同一页面中。

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

为了完整起见,我在登录失败时添加了一条面部消息,否则最终用户将不知道为什么页面似乎在没有任何形式的反馈的情况下重新加载。此消息将显示在<h:messages globalOnly="true">

另见:

相关问题