Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 475
SnIpY Avatar asked Nov 23 '11 09:11

SnIpY


1 Answers

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>
like image 180
Ramesh PVK Avatar answered Oct 24 '22 18:10

Ramesh PVK