如何在spring mvc拦截器中validation会话

我是spring framework的新手。在我的代码中,我使用拦截器检查会话是否存在。如果会话存在,我允许调用控制器,否则我重定向登录页面。 以下是我的代码。

@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; } } 

但是这段代码没有成功重定向。我收到以下错误,

 In Mozilla i get below error The page is not redirecting properly In chorme i get below error? This web page has redirect loop 

如何解决这个问题?非常感谢任何帮助!

只是一个疯狂的猜测,因为你忘了说你的拦截器是如何配置的。 我认为这可能是由拦截器应用于登录页面index

如果这是真的,任何页面都会要求浏览器重定向到index页面,但index页面本身会向浏览器发送重定向请求。

正确的方法是配置拦截器以忽略登录页面

 @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; } } 

您还可以使用SpringMVC配置使拦截器不应用于登录页面

但无论如何,如果你想构建一个认真的应用程序,我的建议是看看Spring Security在Spring MVC应用程序中很好地集成,并附带一些示例以避免上述问题(以及其他…)