How to redirect to another page when already authenticated user accesses login page

后端 未结 2 1975
情歌与酒
情歌与酒 2020-12-19 10:31

I was wondering if it was possible to redirect users if a certain c:if clausule is true?



        
相关标签:
2条回答
  • 2020-12-19 10:48

    Apart from the Filter approach, you can also use <f:event type="preRenderView">. Put this somewhere in top of the view:

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

    And add this listener method to the LoginController:

    public void checkAuthentication() throws IOException {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    
        if (externalContext.getUserPrincipal() != null) {
            externalContext.redirect(externalContext.getRequestContextPath() + "/index.xhtml");
        }
    }
    

    That's all.

    See also:

    • Is there any easy way to preprocess and redirect GET requests?
    0 讨论(0)
  • 2020-12-19 10:51

    Yes it is possible.

    But, I would suggest you to apply filter for /login.jsp and in the filter forward to the other page if the user has already logged in.

    Here is the example which tells how to do this using filter:

    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()
       {
    
       }
    }
    

    Add this filter enty in the 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>
    
    0 讨论(0)
提交回复
热议问题