6

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

<c:if test="#{loginController.authenticated}">
 //redirect to index page
</c:if>
Ramesh PVK
  • 15,200
  • 2
  • 46
  • 50
SnIpY
  • 662
  • 2
  • 10
  • 27

2 Answers2

9

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>
Ramesh PVK
  • 15,200
  • 2
  • 46
  • 50
  • Well, I want this if statement on my login page, s if users try to access that page if they are already logged in, they just get transferred to another page – SnIpY Nov 23 '11 at 09:43
  • What would be the best approach to do so? using javascript or does JSF have any build in features for that? – SnIpY Nov 23 '11 at 09:51
  • 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. – Ramesh PVK Nov 23 '11 at 09:53
  • Any example on how to accomplish this? – SnIpY Nov 23 '11 at 10:32
5

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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555