自定义拦截器类
public class SessionInterceptor extends HandlerInterceptorAdapter {
public SessionInterceptor() {
// TODO Auto-generated constructor stub
}
private List<String> excludedUrls;
//通过属性注册不需要过滤的url list
public void setExcludedUrls(List<String> excludedUrls) {
this.excludedUrls = excludedUrls;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String requestUrl = request.getRequestURI();
//排除不需要过滤的URL
for(String url:excludedUrls) {
if(requestUrl.endsWith(url)) {
return true;
}
}
//获取当前的会话session
HttpSession session = request.getSession();
if(session.getAttribute("userid") == null) {
//若登录session过期或不存在就跳转到login页面
request.getRequestDispatcher("/login.jsp").forward(request, response);
return false;
}
return true;
}
}
springmvc-servlet.xml 拦截器注册
<mvc:interceptors>
<mvc:interceptor>
<!--
/*的意思是所有文件夹及里面的子文件夹
/是所有文件夹,不含子文件夹
/是web项目的根目录
-->
<mvc:mapping path="/**" />
<!-- 需排除拦截的地址 -->
<!-- <mvc:exclude-mapping path="/login"/> -->
<bean id="commonInterceptor" class="com.skcc.chart.interceptor.SessionInterceptor">
<property name="excludedUrls">
<list>
<value>/login</value>
</list>
</property>
</bean> <!--这个类就是我们自定义的Interceptor -->
</mvc:interceptor>
<!-- 当设置多个拦截器时,先按顺序调用preHandle方法,然后逆序调用每个拦截器的postHandle和afterCompletion方法 -->
</mvc:interceptors>
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<mvc:resources mapping="/resources/**" location="/resources/" order="0" />
<mvc:resources mapping="/js/**" location="/js/" order="0" />
<mvc:resources mapping="/css/**" location="/css/" order="0" />
<!-- Spring MVC不处理静态资源 -->
<mvc:default-servlet-handler />
<!-- 配置注解的处理器映射器和处理器适配器 -->
<mvc:annotation-driven ></mvc:annotation-driven>
HandlerInterceptorAdapter不能拦截WEB-INF目录以外的jsp文件;若需拦截默认index.jsp;可以将index.jsp移动目录到WEB-INF下即可;
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。