拦截器的作用:拦截器是动态拦截Action调用的对象。
它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,
也可以在一个action执行前阻止其执行。同时也是提供了一种可以提取action中可重用的部分的方式。
编写拦截器类实现HandlerInterceptor方法 重写preHandle方法(如有需要可重写其他方法) 在spring-mvc中配置拦截器需要拦截的路径和不需要拦截的路径
代码示例
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle ( HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String url = request. getRequestURI ( ) ;
if ( url. endsWith ( "/login" ) || url. endsWith ( "/logout" ) ) {
return true ;
}
User login_user = ( User) request. getSession ( ) . getAttribute ( "login_user" ) ;
if ( login_user != null) {
if ( "超级管理员" . equals ( login_user. getRole ( ) ) ) {
return true ;
} else {
response. sendRedirect ( request. getContextPath ( ) + "/admin/error/privilege.jsp" ) ;
return false ;
}
} else {
response. sendRedirect ( request. getContextPath ( ) + "/admin/error/privilege.jsp" ) ;
return false ;
}
}
}
<!--spring-mvc.xml中配置拦截器-->
<mvc: interceptors>
<mvc: interceptor>
<!-- 配置拦截路径 - - >
<mvc:mapping path="/admin/**"/>
<!-- 不拦截静态资源 -->
<mvc:exclude-mapping path="/admin/css/**"/>
<mvc:exclude-mapping path="/admin/jquery/**"/>
<mvc:exclude-mapping path="/admin/js/**"/>
<mvc:exclude-mapping path="/admin/images/**"/>
<bean class="com.bookstore.admin.interceptor.LoginInterceptor"></bean>
</mvc: interceptor>
</mvc: interceptors>