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

我正在尝试使用基于表单的身份validation的HttpServletRequest.login。

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

在此先感谢您的帮助。

代码:

web.xml中:

 FORM security  /faces/loginwithlogin.xhtml /faces/noaut.xhtml   

页面loginwithlogin.xhtml

   Authentication    Login :  

Mot de passe :

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

支持豆:

 @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)); } } } 

在基于容器管理表单的身份validation的情况下,登录页面由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 ;否则需要使用不同的方法与 ) 。