Sendredirect Error in Interceptor

-2

I am studying Java Web and need to make an application with access restriction. Restricting access if the user is not logged in (ie the session created), if the user accesses a URL without being logged in, he should redirect to the login screen. However I am getting a response from the browser that many redirects have been made.

Would anyone know how to guide me because of this error?

Authorization Interceptor.java:

public class AutorizacaoInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object controller) throws Exception {
        if(!request.getRequestURI().endsWith("login") && null != request.getSession().getAttribute("userId")){
            return true;
        }

        response.sendRedirect("login");
        return false;
    }

}

dispatcher-servlet.xml:

<context:component-scan base-package="br.com.infnet" />
<mvc:annotation-driven />
<bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/WEB-INF/jsp/"
      p:suffix=".jsp" />
<mvc:resources mapping="/assets/**" location="/assets/"/>

<mvc:interceptors>
    <bean class="br.com.infnet.model.AutorizacaoInterceptor" />
</mvc:interceptors>

    
asked by anonymous 16.11.2016 / 23:33

1 answer

1

You have an infinite loop of redirects to the login page. By the logic of your if on the interceptor, you handled the cases

  • Not the login page and is already logged in
  • All other cases
  • Missing the case

  • It's the login page and I'm not logged in (you can not fall into case 2 above, otherwise it will give infinite loop, which is what is happening).
  • You might want to use a different logic with the or operator instead of and (eg if login page or logged in), or it may be better to break logic in 2 ifs to ensure that you will handle all possible combinations. If necessary, draw a table on paper with all cases: -)

                login    outras páginas
    logado      ______ | ______
    deslogado   ______ | ______
    

    Fill in and see if the code does what you want.

        
    16.11.2016 / 23:53