JSF 2.0:如何在使用HttpServletRequest.login后重定向到受保护的页面

时间:2012-09-03 10:07:48

标签: java authentication jsf-2

我正在尝试将HttpServletRequest.login与基于表单的身份验证一起使用。

一切正常(容器告诉登录/密码是否良好),除了在用户输入登录后,我不知道如何将用户重定向到他要求的受保护页面(登录表单是重新显示)。怎么做?

提前感谢您的帮助。

代码:

的web.xml:

<login-config>
    <auth-method>FORM</auth-method>
    <realm-name>security</realm-name>
    <form-login-config>
        <form-login-page>/faces/loginwithlogin.xhtml</form-login-page>
        <form-error-page>/faces/noaut.xhtml</form-error-page>
    </form-login-config>
</login-config>

Page loginwithlogin.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:f="http://java.sun.com/jsf/core">
    <h:head>
        <title>Authentication</title>
    </h:head>
    <h:body>
        <h:form>
            Login :
            <h:inputText value="#{login.login}" required="true" />
            <p/>
            Mot de passe :
            <h:inputSecret value="#{login.password}" required="true" />
            <p/>
            <h:commandButton value="Connexion" action="#{login.submit}">
                 <f:ajax execute="@form" render="@form" />
            </h:commandButton>
            <h:messages />
        </h:form>
    </h:body>
</html>

更新:没有Ajax它不起作用。

支持bean:

@Named
@SessionScoped
public class Login implements Serializable {
  private String login;
  private String password;
  // getters and setters 
  ...

  public void submit() {
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletRequest request = 
            (HttpServletRequest) context.getExternalContext().getRequest();
    try {
        request.login(login, mdp);
        context.addMessage(null, 
                new FacesMessage(FacesMessage.SEVERITY_INFO, 
                "OK", null));
    } catch (ServletException e) {
        context.addMessage(null, 
                new FacesMessage(FacesMessage.SEVERITY_ERROR, 
                "Bad login", null));
    }
  }

}

1 个答案:

答案 0 :(得分:5)

如果是基于容器管理的表单身份验证,则登录页面位于由RequestDispatcher#forward()打开的封面下,因此原始请求URI可用作请求属性,其名称由RequestDispatcher#FORWARD_REQUEST_URI标识。请求属性(基本上是请求范围)由ExternalContext#getRequestMap()提供在JSF中。

因此,这应该做:

private String requestedURI;

@PostConstruct
public void init() {
    requestedURI = FacesContext.getCurrentInstance().getExternalContext()
        .getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);

    if (requestedURI == null) {
        requestedURI = "some/default/home.xhtml";
    }
}

public void submit() throws IOException {
    // ...

    try {
        request.login(username, password);
        externalContext.redirect(requestedURI);
    } catch (ServletException e) {
        context.addMessage(null, 
                new FacesMessage(FacesMessage.SEVERITY_ERROR, 
                "Bad login", null));
    }
}

您只需要创建bean @ViewScoped(JSF)或@ConversationScoped(CDI)而不是@SessionScoped(绝对不是@RequestScoped;否则需要采用不同的方法与<f:param><f:viewParam>)一起使用。