我想在会话失效时重定向到登录。我的servelt.xml如下。
<mvc:interceptors>
<bean class="com.package.login.LoginIntercepter" />
</mvc:interceptors>
拦截器:
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
HashMap details = (HashMap)session.getAttribute("details");
System.out.println("Pre-handle ::"+request.getRequestURI());
if(details!=null){
/*For Checking the Session
* -----Start-----*/
return true;
}else{
response.sendRedirect("Login");//Here Login is action Name which is Mapped in Login Controller
return false;
}
}
登录控制器:
@RequestMapping(value="/Login", method=RequestMethod.GET)
public String loginMethodWithoutaction(HttpServletRequest request,HttpServletResponse response)
{
String page="login";
HttpSession session = request.getSession();
HashMap details = (HashMap)session.getAttribute("details");
if(details!=null)
page = "redirect:/Home";
return page;
}
如果会话无效,则必须重定向“登录”页面。否则它必须转到Home Controller.But它不工作。每当应用程序启动时,消息会多次打印,最后它会给堆栈溢出。
答案 0 :(得分:2)
邮件多次打印,因为当重定向请求再次被截获并且您的会话仍然为空时因为控制器方法尚未执行。
您必须创建一个方法,在您的控制器中成功登录时设置details
属性。
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession(false);
String path = request.getRequestURI().substring(request.getContextPath().length());
if(path.equals("/Login")){
return true;
}
else if(session == null || session.getAttribute("details") == null) {
request.setAttribute("emassage", "login failed");
throw new LoginFailException("login failed");
}else{
return true;
}
}
LoginFailExceptionClass:
public class LoginFailException extends Exception{
private static final long serialVersionUID = 1L;
public LoginFailException(String message) {
super(message);
}
}
在Controller中处理异常并重定向到登录失败页面:
@ExceptionHandler(LoginFailException.class)
public String redirectToLogin(){
return "redirect:/login";
}
答案 1 :(得分:0)
我认为这是你的Spring配置并不好。尝试类似的东西:
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<ref bean="loginIntercepter"/>
</property>
您必须在spring文件中声明您的loginItercepter