首页 > 代码库 > springmvc 拦截器

springmvc 拦截器

1 拦截器概念和struts2一致

2 实现拦截器

  a 实现handlerinterceptor接口

 

 

public class MyInterceptor implements HandlerInterceptor {

    //在请求处理的方法之前执行
    //如果返回true 那么执行下一个拦截器,如果返回false那么不去执行下一个拦截器
    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("-------处理前------");
        return true;
    }
    //在请求处理的方法执行之后执行
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2, ModelAndView arg3) throws Exception {
        System.out.println("-------处理后--------");
        // TODO Auto-generated method stub    
    }
    //在DispatcherServlet处理后执行---清理工作
    @Override
    public void afterCompletion(HttpServletRequest arg0,
            HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        
        // TODO Auto-generated method stub
        
    }
}

b 配置拦截器

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        <!-- configure the InternalResourceViewResolver -->
    
    <context:component-scan base-package="com.sgcc.controller"></context:component-scan>
    <!-- 拦截器的配置 -->
    <mvc:interceptors>
        <mvc:interceptor>
        <!-- 包括路径及其子路径
            如果是/admin/* 拦截的是/admin/add  /admin/list etc /admin/user/add不会被拦截
            如果是/admin/** 上面都能拦截
         -->
            <mvc:mapping path="/**"/>
            <!-- 对应的拦截器 -->
            <bean class="com.sgcc.interceptor.MyInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>
</beans>

 

springmvc 拦截器