当会话过期时,如何在Spring MVC中全局转发会话Expired.jsp

时间:2014-07-16 10:20:18

标签: spring-mvc

我是Spring MVC的新手。当会话过期时,我不知道如何在Spring MVC globaly中转发sessionExpired.jsp。 我google了很多,但我没有得到任何解决方案。我得到的是他们正在使用spring security。在我们的应用程序中,我们没有使用Spring安全性。

请提供一些示例代码。

1 个答案:

答案 0 :(得分:0)

如果您添加此代码,则应解决您的问题

<security:session-management invalid-session-url="SessionExpired.jsp" session-authentication-error-url="AlreadyLoggedIn.jsp">
<security:concurrency-control max-sessions="1" expired-url="SessionIsDuplicated.jsp" error-if-maximum-exceeded="false" />
</security:session-management>

在不使用安全性的情况下,Spring MVC中有两种方法可以在Servlet中使用HandlerInterceptorAdapter或Filters。

使用HandlerInterceptorAdapter

在springContext.xml

<mvc:interceptors>
<bean class="com.nalashaa.interceptor.SessionValidatorInterceptor" />
</mvc:interceptors>

package com.nalashaa.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Component
public class SessionValidatorInterceptor extends HandlerInterceptorAdapter {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (request.getServletPath().equals("/login.htm")) {  //for Login Page
        return true;
    }
if(request.getSession().getAttribute("userName")!=null){
return true;
}else{
response.sendRedirect("login.htm");
return false;
} 
}
}

使用过滤器

在web.xml中

<filter>  
<filter-name>SessionValidatorFilter</filter-name>  
 <filter-class>com.nalashaa.filter.SessionValidatorFilteFilter</filter-class>  
</filter>  
<filter-mapping>  
 <filter-name>SessionValidatorFilter</filter-name>  
 <url-pattern>/*</url-pattern>  
</filter-mapping>   

package com.nalashaa.filter;  

import java.io.IOException;  
import javax.servlet.Filter;  
import javax.servlet.FilterChain;  
import javax.servlet.FilterConfig;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.RequestDispatcher;  
import javax.servlet.ServletException;  
import javax.servlet.ServletRequest;  
import javax.servlet.ServletResponse;  

public class SessionValidatorFilter implements Filter {  

public void init(FilterConfig filterConfig) throws ServletException {  
// initialization 
} 


public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {  
 if(((HttpServletRequest)request).getRequestedSessionId() != null && ((HttpServletRequest)request).isRequestedSessionIdValid() == false) {  
  RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/login.jsp");  
  requestDispatcher.forward(request, response);  
 }else {  
  chain.doFilter(request, response);  
 }  
}  

public void destroy() {  
//Destroy code
}  

}