Spring Mvc session拦截器实现

时间:2021-01-14 08:29:23

Spring Mvc拦截器实现session过期跳转到登录页面

  • 配置拦截器
    <mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**/*.html"/>
<bean class="com.rrtong.frame.plugins.SecurityInterceptor">
<property name="excludedUrls">
<list>
<value>/login.html</value>
<value>/auth.html</value>
</list>
</property>
</bean>
</mvc:interceptor>
</mvc:interceptors>
  • 实现拦截器
package com.rrtong.frame.plugins;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import com.rrtong.util.Constants; /*实现登录访问验证拦截器*/
public class SecurityInterceptor implements HandlerInterceptor {
/*过滤不需要验证的url*/
private List<String> excludedUrls; public void setExcludedUrls(List<String> excludedUrls) {
this.excludedUrls = excludedUrls;
} @Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
String requestUri = request.getRequestURI(); for (String url : excludedUrls) {
if (requestUri.endsWith(url)) {
return true;
}
} /*判断是否需要过滤的页面*/
HttpSession session = request.getSession(); if(session.getAttribute(Constants.Session.CURRENT_USER_ATTR_NAME) == null){
/*跳转到登录页*/
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response); return false;
}
return true;
} @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object arg2, ModelAndView arg3) throws Exception {
} @Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object arg2, Exception arg3)
throws Exception {
}
}