Redirect using Spring boot interceptor
Asked Answered
L

4

9

I have created a web app using spring boot and freemarker and implemented interceptor(HandlerInterceptorAdapter).

Inside the interceptor, when user is not logged then it will redirect to login page. This works fine. But the problem is that the controller is being executed first before redirecting to the login page.

My Interceptor Code:

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        User userSession = (User) request.getSession().getAttribute("user");
        if (userSession == null) {
            response.sendRedirect("/login");
        }
    }

Controller class(after response.sendRedirect, this controller is still being excuted). Why? I'm stack in with this problem.

@RequestMapping("/home")
    public String home(Model model, HttpServletRequest httpServletRequest) {

        String returnPage = "home-admin";

        User user = (User) httpServletRequest.getSession().getAttribute("user");
        if(user != null){
            String accessType = accessTypeRepository.getAccessType(user.getAccessId());
            if(StrUtil.isEqual(accessType, AccessTypeConst.MANAGER.getType())){
                returnPage = "home-manager";
            }
        }
        return returnPage;
    }
Lanell answered 24/6, 2017 at 19:43 Comment(0)
O
24

You should return false from your interceptor if you are done with execution.

Returns: true if the execution chain should proceed with the next interceptor or the handler itself. Else, DispatcherServlet assumes that this interceptor has already dealt with the response itself.

http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/HandlerInterceptor.html

Change

if (userSession == null) {
    response.sendRedirect("/login");
}

to

if (userSession == null) {
    response.sendRedirect("/login");
    return false;
}
Okay answered 24/6, 2017 at 20:7 Comment(4)
Woahh!! I got stack with this problem for a couple of hours and the solution is just as simple as this. Thanks a lot man, you made my day.Lanell
I'm glad it solves your problem. Would you accept this as answer?Okay
how would you handle multiple prehandle calls since its redirecting it means this handler will also execute second time?Bilious
@Bilious you can have as many interceptors as you want. If you just return true, next interceptor will handle it.Okay
D
3

In interceptor preHandle() function.

return false to let Spring framework assume that request has been handled by the spring interceptor itself and no further processing is needed.

return true to let Spring know to process the request through another spring interceptor or to send it to handler method (Your Controller Function) if there are no further spring interceptors.

So, In this case return false at end in interceptor preHandle function.

Disinherit answered 8/12, 2018 at 6:12 Comment(0)
C
1

When i use return false, i take "Error: Exceeded maxRedirects. Probably stuck in a redirect loop http://localhost:8080/api/login"

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(true){
            response.sendRedirect("/api/login");
            return false;
        }
        return true;
    }
Cumulative answered 6/7, 2020 at 19:59 Comment(0)
M
-1

for anyone who’s searching for the answer to the same question from @calisci That’s probably cuz u r NOT excluding the redirect url from request Try add this before redirect

if(!request.getRequestURL().toString().endswith("/put redirect url here")

Glad if help.

Monochrome answered 22/11, 2022 at 13:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.