Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect using Spring boot interceptor

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;
    }
like image 265
kevenlolo Avatar asked Nov 28 '22 22:11

kevenlolo


1 Answers

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;
}
like image 79
Bunyamin Coskuner Avatar answered Dec 04 '22 02:12

Bunyamin Coskuner