Sendredirect error in Interceptor

Asked

Viewed 108 times

-2

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

Someone could tell me why you made this mistake?

Authorize ointerceptor.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>

Erro send redirect

  • Please do not paste sprint code screens. Post formatted code and error description instead.

1 answer

1

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

  1. Not the login page and is already logged in
  2. All other cases

The case has not been handled

  1. It is the login page and I am not logged in (can not fall in case 2 above, otherwise will give infinite loop, which is what is happening).

Maybe you wanted to use a different logic, with the operator or instead of and (ex.: if login page or already logged in), or it might be better to break the logic into 2 ifs to ensure that you handle all possible combinations. If necessary, draw a table on paper with all cases :-)

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

Fill in and make sure the code does what you want.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.