首页 > 代码库 > spring filter and interceptor

spring filter and interceptor

Spring Filter  过滤器   和 Interceptor 拦截器

环境 : maven 工程 , 已配好springmvc 的运行环境 

一、Filter 的实现 

1、自定义一个类 MyFilter , 实现Filter 接口 。

package com.crystal.api.filter;

import javax.servlet.*;
import java.io.IOException;

/**
 * Created by Administrator on 2017/4/28.
 */
public class MyFilter implements Filter {
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        System.out.println("init method");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        System.out.println("detail implement ...");
    }

    @Override
    public void destroy() {

    }
}

注 :Fliter是javax.servlet-api jar包中的Filter 。

  maven对应的jar包 :

  <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>

 

2、将自定义的类配置到配置文件中 web.xml 

 

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Archetype Created Web Application</display-name>


<!-- spring mvc dispatcher filter-->
<servlet>
<display-name>Spring Dispatcher Servlet</display-name>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/WEB-INF/spring/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>


<!--encoding filter-->
<filter>
<display-name>CharacterEncodingFilter</display-name>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- define filter -->
<filter>
<filter-name>defineFilter</filter-name>
<filter-class>com.crystal.api.filter.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>defineFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>



</web-app>

 

3. 启动工程,查看自定义拦截器是否生效 。

 

 

 

二 、spring 拦截器

1、自定义拦截器 类 DefineHandlerInterceptor , 继承  HandlerInterceptorAdapter

 

package com.crystal.api.interceptor;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

/**
 * Created by Administrator on 2017/4/28.
 */
public class DefineHandlerInterceptor extends HandlerInterceptorAdapter {


    /**
     * 请求执行之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("请求执行之前");
        System.out.println("可以做一些打印头信息之类的log");
        return true;
    }


    /**
     * 请求执行之后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("请求执行之后");
        System.out.println("可以修改返回的视图");
    }



    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}

注 : preHandle 方法在 请求进来时,执行业务流程之前执行 。 返回值为 true : 则继续执行业务逻辑  ;返回值为false :则           整个请求就结束了,不会在继续执行业务逻辑 。

 

 

2、配置文件 applicationContext.xml   ,以下贴图只是针对拦截器的配置信息,其他的springmvc的配置,请另做配置 。

<?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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
           http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">


    <!-- Controller and interceptor mapping for API -->
    <mvc:interceptors>
        <!-- Internationalisation interceptor -->
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>

        <mvc:interceptor>
            <mvc:mapping path="/v2/**"/>
            <mvc:exclude-mapping path="/v2/api-docs/**"/>
            <ref bean="defineHandlerInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

    <bean id="defineHandlerInterceptor"
          class="com.crystal.api.interceptor.DefineHandlerInterceptor">
    </bean>


</beans>

注 :<mvc:interceptors> 标签是拦截器的标识 。 里面可以配置多个拦截器 。配置多个拦截器的顺序是从上往下执行。<具体的prehandle 和 posthandle 方法的执行顺序,你可以多配置几个拦截器执行看结果> 

     拦截器配置方式 :(1)、如上的国际化拦截器,直接bean的方式:代表拦截所有的请求

                             (2)、<mvc:interceptor> 方法 , 用<mvc:mapping>标签配置你要拦截的url,可用正则表达式,  <mvc:exclude-mapping> 标签配置配置你要排除的某个url 。ref 指向这个拦截器具体的拦截逻辑<就是自定义的拦截器类>

 

3、启动工程,访问某个你拦截的url

 

过滤器和拦截器写的比较简单。待以后完善 。因为我也只是一个初级的程序员。哈哈哈哈

 

 

 

  

 

spring filter and interceptor