一、拦截器和过滤器


(1)过滤器:

    依赖于servlet容器,是JavaEE标准,是在请求进入容器之后,还未进入Servlet之前进行预处理,并且在请求结束返回给前端这之间进行后期处理。在实现上基于函数回调,可以对几乎所有请求进行过滤,但是缺点是一个过滤器实例只能在容器初始化时调用一次。使用过滤器的目的是用来做一些过滤操作,获取我们想要获取的数据,比如:在过滤器中修改字符编码;在过滤器中修改HttpServletRequest的一些参数,包括:过滤低俗文字、危险字符等

(2)拦截器:

    拦截器不依赖与servlet容器,依赖于web框架,在SpringMVC中就是依赖于SpringMVC框架。在实现上基于Java的反射机制,属于面向切面编程(AOP)的一种运用。由于拦截器是基于web框架的调用,因此可以使用spring的依赖注入(DI)获取IOC容器中的各个bean,进行一些业务操作,同时一个拦截器实例在一个controller生命周期之内可以多次调用。但是缺点是只能对controller请求进行拦截,即⑴请求还没有到controller层时进行拦截,⑵请求走出controller层次,还没有到渲染时图层时进行拦截,⑶结束视图渲染,但是还没有到servlet的结束时进行拦截。对其他的一些比如直接访问静态资源的请求则没办法进行拦截处理,拦截器功在对请求权限鉴定方面确实很有用处

二、代码

(1)程序框架,只需关注红线中四个文件

spring boot过滤器实现验签 springboot过滤器的作用_spring boot过滤器实现验签

(2)过滤器配置

package com.server.config.filter;

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

/**
 * Created by c00415904 on 2018/6/28.
 */
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("myFilter init.....");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("myFilter doFilter.....");
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("myFilter destroy.....");
    }
}
package com.server;

import com.server.config.filter.MyFilter;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

import javax.servlet.Filter;

/**
 * Created by c00415904 on 2018/6/28.
 */
@SpringBootConfiguration
public class MyfilterConfig {
    @Bean
    public FilterRegistrationBean filterRegistrationBean(){
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(getMyFilter());
        registrationBean.addUrlPatterns("/*");
        registrationBean.addInitParameter("paramName","paramValue");
        registrationBean.setName("myFilter");
        return registrationBean;
    }
    @Bean(name="myfilter")
    public Filter getMyFilter(){
        return new MyFilter();
    }
}

此类的目录一般要与Application相同,当然也可以通过配置一些显示路径能够适配,为了简单就放在一起就OK。

(3)拦截器

package com.server.config.Intercept;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * Created by c00415904 on 2018/6/27.
 */
@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("hello preHandler......");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("hello postHandler......");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("hello afterCompletionHandler......");
    }
}
package com.server;

import com.server.config.Intercept.MyInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * Created by c00415904 on 2018/6/27.
 */
@SpringBootConfiguration
public class MySpringMVCConfig extends WebMvcConfigurerAdapter {
    @Autowired
    private MyInterceptor myInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(myInterceptor).addPathPatterns("/**");
    }
}

此类的目录简单与Application相同。

(4)程序结果

2018-06-28 19:55:29.484 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Initializing servlet 'dispatcherServlet'
2018-06-28 19:55:29.485 [http-nio-8080-exec-1] INFO  o.a.c.core.ContainerBase.[Tomcat].[localhost].[/] - Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-06-28 19:55:29.485 [http-nio-8080-exec-1] INFO  org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcherServlet': initialization started
2018-06-28 19:55:29.486 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'multipartResolver'
2018-06-28 19:55:29.486 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Using MultipartResolver [org.springframework.web.multipart.support.StandardServletMultipartResolver@b829584]
2018-06-28 19:55:29.487 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver'
2018-06-28 19:55:29.495 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.cache.config.internalCacheAdvisor'
2018-06-28 19:55:29.496 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
2018-06-28 19:55:29.499 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver'
2018-06-28 19:55:29.499 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Unable to locate LocaleResolver with name 'localeResolver': using default [org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver@1c6767c6]
2018-06-28 19:55:29.499 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.web.servlet.theme.FixedThemeResolver'
2018-06-28 19:55:29.509 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.cache.config.internalCacheAdvisor'
2018-06-28 19:55:29.509 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
2018-06-28 19:55:29.511 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.web.servlet.theme.FixedThemeResolver'
2018-06-28 19:55:29.511 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Unable to locate ThemeResolver with name 'themeResolver': using default [org.springframework.web.servlet.theme.FixedThemeResolver@582bfa21]
2018-06-28 19:55:29.512 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'requestMappingHandlerMapping'
2018-06-28 19:55:29.512 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'viewControllerHandlerMapping'
2018-06-28 19:55:29.512 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'beanNameHandlerMapping'
2018-06-28 19:55:29.512 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'resourceHandlerMapping'
2018-06-28 19:55:29.512 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'defaultServletHandlerMapping'
2018-06-28 19:55:29.512 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'faviconHandlerMapping'
2018-06-28 19:55:29.512 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'requestMappingHandlerAdapter'
2018-06-28 19:55:29.512 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'httpRequestHandlerAdapter'
2018-06-28 19:55:29.512 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'simpleControllerHandlerAdapter'
2018-06-28 19:55:29.513 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'errorAttributes'
2018-06-28 19:55:29.513 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'handlerExceptionResolver'
2018-06-28 19:55:29.513 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator'
2018-06-28 19:55:29.520 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.cache.config.internalCacheAdvisor'
2018-06-28 19:55:29.521 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
2018-06-28 19:55:29.521 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator'
2018-06-28 19:55:29.521 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Unable to locate RequestToViewNameTranslator with name 'viewNameTranslator': using default [org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator@782c5e3a]
2018-06-28 19:55:29.522 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'beanNameViewResolver'
2018-06-28 19:55:29.522 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'mvcViewResolver'
2018-06-28 19:55:29.522 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'defaultViewResolver'
2018-06-28 19:55:29.522 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'viewResolver'
2018-06-28 19:55:29.524 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.web.servlet.support.SessionFlashMapManager'
2018-06-28 19:55:29.552 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.cache.config.internalCacheAdvisor'
2018-06-28 19:55:29.553 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
2018-06-28 19:55:29.554 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.web.servlet.support.SessionFlashMapManager'
2018-06-28 19:55:29.554 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Unable to locate FlashMapManager with name 'flashMapManager': using default [org.springframework.web.servlet.support.SessionFlashMapManager@435b33b4]
2018-06-28 19:55:29.554 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Published WebApplicationContext of servlet 'dispatcherServlet' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcherServlet]
2018-06-28 19:55:29.554 [http-nio-8080-exec-1] INFO  org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcherServlet': initialization completed in 68 ms
2018-06-28 19:55:29.554 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Servlet 'dispatcherServlet' configured successfully
2018-06-28 19:55:29.572 [http-nio-8080-exec-1] DEBUG o.s.boot.web.filter.OrderedRequestContextFilter - Bound request context to thread: org.apache.catalina.connector.RequestFacade@84a924d
myFilter doFilter.....
2018-06-28 19:55:29.575 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'dispatcherServlet' processing GET request for [/num]
2018-06-28 19:55:29.578 [http-nio-8080-exec-1] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Looking up handler method for path /num
2018-06-28 19:55:29.580 [http-nio-8080-exec-1] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Returning handler method [int com.server.controller.TestController.num()]
2018-06-28 19:55:29.580 [http-nio-8080-exec-1] DEBUG o.s.b.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'testController'
2018-06-28 19:55:29.580 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Last-Modified value for [/num] is: -1
hello preHandler......
2018-06-28 19:55:29.594 [http-nio-8080-exec-1] INFO  com.server.controller.TestController - get num
2018-06-28 19:55:29.604 [http-nio-8080-exec-1] DEBUG org.mybatis.spring.SqlSessionUtils - Creating a new SqlSession
2018-06-28 19:55:29.609 [http-nio-8080-exec-1] DEBUG org.mybatis.spring.SqlSessionUtils - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@632df33c] was not registered for synchronization because synchronization is not active
2018-06-28 19:55:29.619 [http-nio-8080-exec-1] DEBUG o.springframework.jdbc.datasource.DataSourceUtils - Fetching JDBC Connection from DataSource
2018-06-28 19:55:29.945 [http-nio-8080-exec-1] DEBUG o.m.spring.transaction.SpringManagedTransaction - JDBC Connection [ProxyConnection[PooledConnection[com.mysql.jdbc.JDBC4Connection@602aedad]]] will not be managed by Spring
2018-06-28 19:55:29.948 [http-nio-8080-exec-1] DEBUG com.server.dao.UserDao.findCount - ==>  Preparing: select count(*) from user_table 
2018-06-28 19:55:29.970 [http-nio-8080-exec-1] DEBUG com.server.dao.UserDao.findCount - ==> Parameters: 
2018-06-28 19:55:29.988 [http-nio-8080-exec-1] DEBUG com.server.dao.UserDao.findCount - <==      Total: 1
2018-06-28 19:55:29.989 [http-nio-8080-exec-1] DEBUG org.mybatis.spring.SqlSessionUtils - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@632df33c]
2018-06-28 19:55:29.989 [http-nio-8080-exec-1] DEBUG o.springframework.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource
2018-06-28 19:55:30.058 [http-nio-8080-exec-1] DEBUG o.s.w.s.m.m.a.RequestResponseBodyMethodProcessor - Written [6] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@483b0690]
hello postHandler......
2018-06-28 19:55:30.059 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
hello afterCompletionHandler......
2018-06-28 19:55:30.059 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Successfully completed request
2018-06-28 19:55:30.060 [http-nio-8080-exec-1] DEBUG o.s.boot.web.filter.OrderedRequestContextFilter - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@84a924d