问题
I am newbie to spring framework.In my code,i use the interceptor for checking the session exists or not.If session exists i allow to call the controller otherwise i redirect the login page. Below is my code.
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Users user=(Users) session.getAttribute("user");
if(user == null)
{
System.err.println("Request Path : ");
response.sendRedirect("index");
return false;
}
else
{
return true;
}
}
but this code not redirect successfully.I am getting the below error,
In Mozilla i get below error
The page is not redirecting properly
In chorme i get below error?
This web page has redirect loop
How to fix this issue?Any help will be greatly appreciated!!!
回答1:
Just a wild guess, because you forgot to say how your interceptor is configured. I think it could be caused by the interceptor being applied to the login page index.
If this is true any page will ask the browser to redirect to index page, but index page itself will send a redirect request to browser.
The correct way is to configure the interceptor to ignore the login page
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
// ignore login page
if (request.getServletPath() == "/index") { // BEWARE : to be adapted to your actual login page
return true;
}
Users user=(Users) session.getAttribute("user");
if(user == null)
{
System.err.println("Request Path : ");
response.sendRedirect("index");
return false;
}
else
{
return true;
}
}
You could also use SpringMVC configuration to have the interceptor not applied to the login page
But anyway, if you want to build a serious application, my advice is to have a look to Spring Security that nicely integrates in a Spring MVC application and comes with a bunch of examples to avoid above problem (and others ...)
来源:https://stackoverflow.com/questions/29598757/how-to-validate-the-session-in-spring-mvc-interceptor