用户使用JSF 2.0登录

我正在尝试 – 使用JSF 2.0 – 以一种巧妙的方式实现登录/记住我/注销管理。 由于传统的<form action="j_security_check" ...方式缺乏灵活性,我决定采用不同的路径,但我发现了一个问题。

通过在应用程序服务器中以及通过在web.xml中正确设置声明性安全性。

登录页面:

           

简单的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"; } 

一切正常,但成功登录后我不知道如何将用户转发到其原始请求。 由于登录页面自动插入客户端请求和“任何”安全资源之间,因此我需要一种方法来了解重定向操作的位置。 request.getRequestURL( )没有帮助,可能是因为RequestDispatcher#forward() (它覆盖了请求url)干预。 您认为这是管理登录过程的合适方式吗? 如果是这样,任何关于这个问题的暗示?

非常感谢!

在登录视图中添加以下行。 它在登录期间存储请求的页面。

  

然后在您的登录bean中获取请求的uri。

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

?faces-redirect=true添加到字符串并返回它。

上面的答案非常有效,只是指出了那些不警惕的人.f:param名称应该在commandButton之类的内部……

    

这似乎只适用于按钮(Mojarra 2.2,Glassfish 4)之间。 您将需要这两个标记javax.servlet.forward.request_urijavax.servlet.forward.query_string以确保您准确地重定向回所有类型的URL(带或不带查询字符串)。 确保您的登录页面中包含类似于以下代码段的内容,即您在web.xml指定用于/login.xhtml/login.xhtml )。

     

然后,您可以在表单提交后检索辅助bean中的两个参数,如下所示

 public String login() { try { String nextPage = "/index.xhtml"; // have a default value in case the user goes to login page directly. ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext(); Map map = ctx.getRequestParameterMap(); String redirect = map.get("redirect"); String queryString = map.get("query_string"); HttpServletRequest request = (HttpServletRequest) ctx.getRequest(); request.login(this.username, this.password); // here login is successful otherwise it would've thrown exception // now let's check the kind of URL our user was going to if (redirect != null && !redirect.isEmpty()) { // if redirect is null, return the default page // please use faces-redirect = true to ensure URL change in the browser if (queryString != null) { nextPage = redirect + "?" + queryString + "&faces-redirect=true"; } else { // there is no query string, nextPage = redirect nextPage = redirect + "&faces-redirect=true"; } // Caveat: You may not need the next lines of code. // I discovered that the `redirect` string has my context path // value in it and so it was'nt redirecting. Remove the context path if (nextPage.contains(request.getContextPath())) { nextPage = nextPage.substring(request.getContextPath().length()); } } } catch (ServletException ex) { Logger.getLogger(SecurityController.class.getName()).log(Level.SEVERE, null, ex); // invalid username or password return "/login.xhtml?failed=true"; // or login error page } return nextPage; } 

我希望这可以帮助别人。