当已经过身份验证的用户访问登录页面时,如何重定向到另一个页面

时间:2011-11-23 09:36:52

标签: security authentication servlets redirect jsf-2

我想知道如果某个c:if clausule是true,是否可以重定向用户?

<c:if test="#{loginController.authenticated}">
 //redirect to index page
</c:if>

2 个答案:

答案 0 :(得分:9)

是的,这是可能的。

但是,如果用户已经登录,我建议您为/login.jsp应用过滤器,并在过滤器中转发到另一页。

以下是使用过滤器说明如何执行此操作的示例:

public class LoginPageFilter implements Filter
{
   public void init(FilterConfig filterConfig) throws ServletException
   {

   }

   public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,   FilterChain filterChain) throws IOException, ServletException
   {
       HttpServletRequest request = (HttpServletRequest) servletRequest;
       HttpServletResponse response = (HttpServletResponse) servletResponse;

       if(request.getUserPrincipal() != null){ //If user is already authenticated
           response.sendRedirect("/index.jsp");// or, forward using RequestDispatcher
       } else{
           filterChain.doFilter(servletRequest, servletResponse);
       }
   }

   public void destroy()
   {

   }
}

在web.xml中添加此过滤器

<filter>
    <filter-name>LoginPageFilter</filter-name>
    <filter-class>
        com.sample.LoginPageFilter
    </filter-class>
    <init-param>
       <param-name>test-param</param-name>
       <param-value>This parameter is for testing.</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>LoginPageFilter</filter-name>
    <url-pattern>/login.jsp</url-pattern>
</filter-mapping>

答案 1 :(得分:5)

Filter方法外,您还可以使用<f:event type="preRenderView">。把它放在视图的顶部:

<f:event type="preRenderView" listener="#{loginController.checkAuthentication}" />

并将此侦听器方法添加到LoginController

public void checkAuthentication() throws IOException {
    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();

    if (externalContext.getUserPrincipal() != null) {
        externalContext.redirect(externalContext.getRequestContextPath() + "/index.xhtml");
    }
}

就是这样。

另见: