Springboot 拦截器 与过滤器配置 (Maven)

  • 导入 pom.xml 包

  • 编写 拦截器类 继承 HandlerInterceptor 并且重写 preHandle、postHandle、 afterCompletion 方法

  1. preHandle: 在业务处理器处理请求之前被调用。预处理,可以进行编码、安全控制、权限校验等处理;
  2. postHandle: 在业务处理器处理请求执行完成后,生成视图之前执行。后处理(调用了Service并返回3. ModelAndView,但未进行页面渲染),有机会修改ModelAndView (这个博主就基本不怎么用了);
  3. afterCompletion: 在DispatcherServlet完全处理完请求后被调用,可用于清理资源等。返回处理(已经渲染了页面);

@Component  // 把普通pojo实例化到spring容器中,相当于配置文件中的
public class TimeInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(((HandlerMethod)handler).getBean().getClass().getName());
        System.out.println(((HandlerMethod)handler).getMethod().getName());
        System.out.println("这里是 Pre");
        request.setAttribute("startTime",new Date().getTime());
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        System.out.println("这里是post");
        System.out.println( "服务处耗时: " + (new Date().getTime() - (Long) request.getAttribute("startTime"))+"毫秒");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        System.out.println("这里是 afterCompletion ");
        System.out.println( "服务处耗时: " + (new Date().getTime() - (Long) request.getAttribute("startTime"))+"毫秒");
        System.out.println("ex is" + ex);
    }
}

-虽然这里注解了@Component 但还是需要在 webConfig 进行再一次配置 让它被Spring 管理


@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired   //注入写的拦截器
    private TimeInterceptor timeInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(timeInterceptor);
    }

//以下编写过滤器

    @Bean
    
    public FilterRegistrationBean characterEncodingFilterRegister(){
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        CharacterEncodingFilter filter = new CharacterEncodingFilter("UTF-8");
        filter.setForceEncoding(true);
        registrationBean.setFilter(filter);

        List urls = new ArrayList<>();
        urls.add("/*");
        registrationBean.setUrlPatterns(urls);

        return registrationBean;
    }



}

  • 以下是 与 SpringMVC 中的过滤器比较
 
        encodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            UTF-8
        
        
            forceEncoding
            true
        
    
    
        encodingFilter
        /*
    

你可能感兴趣的:(Springboot 拦截器 与过滤器配置 (Maven))