Java Filter to redirect users who are not logged in to login page

28,023

Solution 1

After response.sendRedirect("/login.jsp"); do return;.

Solution 2

I believe that you should either invoke sendRedirect OR doFilter. E.g.

if (requiresLogin)
  response.sendRedirect("/login.jsp");
else
  chain.doFilter(req,resp);
Share:
28,023
Shamik
Author by

Shamik

I am a learner. Currently Tech Lead @twilio. Know a thing or two about python and java development.

Updated on July 09, 2022

Comments

  • Shamik
    Shamik almost 2 years

    I was trying to make a filter to stop users who are not logged in from accessing certain pages.For this i made a filter class with the following doFilter method

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    String url = request.getRequestURI();
    boolean allowedRequest = false;
    
    System.out.println(url);
    
    if(urlList.contains(url)) {
        allowedRequest = true;
        System.out.println("in list");
    }
    
    if (!allowedRequest) {
        Object o = request.getSession().getAttribute("UserInfo");
        if (null == o) {
            System.out.println("Hey i am in");
            response.sendRedirect("/login.jsp");
        }
    }
    
    chain.doFilter(req, res);
    
    } // end of doFilter
    

    To allow the pages which doesnot need the user to be logged in i created an arraylist url-list in init()

    Now a very strange stupid thing is happening. suppose i have two pages home.jsp and dcr.jsp. When i try to access home.jsp without logging in the i am successfully redirected to login.jsp but when i am trying to access dcr.jsp it is not redirected although it enters the loop if(null == o) which i can understand because i am getting that line printed in console.THis is the output that i get in the server This is the output that i get in the server

    /dcrmaintenance.jsp
    
    Hey i am in
    

    Which tells me that the null == o was true.

    The page dcr.jsp accesses a session object and since the user is not logged in it is getting java.lang.NullPointerException as expected but i cannot understand why is the redirection not taking place even after entering the loop.If someone can pt out where i am making a mistake it would be appreciated.

  • Shamik
    Shamik about 12 years
    I didnt have any other filter.The other solution worked.But i will check out how i can use security constraints! thanks.