美文网首页
filter intercepter aspect

filter intercepter aspect

作者: hehehehe | 来源:发表于2021-07-05 19:25 被阅读0次
    import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
    import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
    import org.springblade.common.filter.PreviewFilter;
    import org.springblade.common.interceptor.SessionInterceptor;
    import org.springblade.core.secure.registry.SecureRegistry;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
    import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    import javax.annotation.Resource;
    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    
    /**
     * Blade配置
     *
     * @author Chill
     */
    @Configuration
    public class BladeConfiguration implements WebMvcConfigurer {
        @Resource
        SessionInterceptor sessionInterceptor;
        @Value("${file.path}")
        private String filePath;
    
        @Bean
        public SecureRegistry secureRegistry() {
            SecureRegistry secureRegistry = new SecureRegistry();
            secureRegistry.setEnabled(true);
            secureRegistry.excludePathPatterns("/blade-auth/**");
            secureRegistry.excludePathPatterns("/blade-log/**");
            secureRegistry.excludePathPatterns("/blade-system/menu/routes");
            secureRegistry.excludePathPatterns("/blade-system/menu/auth-routes");
            secureRegistry.excludePathPatterns("/blade-system/menu/top-menu");
            secureRegistry.excludePathPatterns("/blade-system/tenant/info");
            secureRegistry.excludePathPatterns("/blade-flow/process/resource-view");
            secureRegistry.excludePathPatterns("/blade-flow/process/diagram-view");
            secureRegistry.excludePathPatterns("/blade-flow/manager/check-upload");
            secureRegistry.excludePathPatterns("/doc.html");
            secureRegistry.excludePathPatterns("/js/**");
            secureRegistry.excludePathPatterns("/webjars/**");
            secureRegistry.excludePathPatterns("/swagger-resources/**");
            secureRegistry.excludePathPatterns("/druid/**");
            return secureRegistry;
        }
    
        @Bean
        @ConditionalOnProperty(value = "blade.preview.enabled", havingValue = "true")
        public PreviewFilter previewFilter() { //这个是注册过滤器
            return new PreviewFilter();
        }
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {//解决跨域的问题
            registry.addMapping("/cors/**")
                .allowedOrigins("*")
                .allowedHeaders("*")
                .allowedMethods("*")
                .maxAge(3600)
                .allowCredentials(true);
        }
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {//将访问路径映射到磁盘路径
    
    //        registry.addResourceHandler("/upload/**").addResourceLocations("file:d:/gangtong/upload/drugferment/resource/");
            registry.addResourceHandler("/file/**").addResourceLocations(filePath);
            //registry.addResourceHandler("/showImg/**").addResourceLocations("file:d:/gangtong/upload/drugferment/");
        }
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {//添加拦截器
    
            registry.addInterceptor(sessionInterceptor).addPathPatterns("/**")
                    .excludePathPatterns("/blade-auth/oauth/token","/blade-auth/oauth/captcha","/blade-auth/oauth/logout");
    
        }
    
        @Bean
        public Jackson2ObjectMapperBuilderCustomizer builderCustomizer() { // jackson的全局配置 日期和long变成string(解决mybatis-plus 生成主健到前台失去精度的问题)
            DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            DateTimeFormatter dateTimeSerializeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            DateTimeFormatter dateTimeDeserializeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            return builder -> {
                // 所有Long类型转换成String到前台
                builder.serializerByType(Long.class, ToStringSerializer.instance);
                builder.serializerByType(LocalDateTime.class, new LocalDateSerializer(dateTimeSerializeFormatter));
            };
        }
    
    }
    
    
    filter
    package com.imooc.web.filter;
    
    import java.io.IOException;
    import java.util.Date;
    
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    
    public class TimeFilter implements Filter {
        public void destroy() {
            System.out.println("time filter destroy");
        }
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            System.out.println("time filter start");
            long start = new Date().getTime();
            chain.doFilter(request, response);
            System.out.println("time filter 耗时:"+ (new Date().getTime() - start));
            System.out.println("time filter finish");
        }
        @Override
        public void init(FilterConfig arg0) throws ServletException {
            System.out.println("time filter init");
        }
    
    }
    
    
    interceptor
    package com.imooc.web.interceptor;
    
    import java.util.Date;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.stereotype.Component;
    import org.springframework.web.method.HandlerMethod;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    @Component
    public class TimeInterceptor implements HandlerInterceptor {
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception {
            System.out.println("preHandle");
            
            System.out.println(((HandlerMethod)handler).getBean().getClass().getName());
            System.out.println(((HandlerMethod)handler).getMethod().getName());
            
            request.setAttribute("startTime", new Date().getTime());
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                ModelAndView modelAndView) throws Exception {
            System.out.println("postHandle");
            Long start = (Long) request.getAttribute("startTime");
            System.out.println("time interceptor 耗时:"+ (new Date().getTime() - start));
    
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
                throws Exception {
            System.out.println("afterCompletion");
            Long start = (Long) request.getAttribute("startTime");
            System.out.println("time interceptor 耗时:"+ (new Date().getTime() - start));
            System.out.println("ex is "+ex);
    
        }
    
    }
    
    
    Aspect
    import java.util.Date;
    
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.springframework.stereotype.Component;
    
    /**
     * @author zhailiang
     *
     */
    @Aspect
    @Component
    public class TimeAspect {
        
        @Around("execution(* com.imooc.web.controller.UserController.*(..))")
        public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
            
            System.out.println("time aspect start");
            
            Object[] args = pjp.getArgs();
            for (Object arg : args) {
                System.out.println("arg is "+arg);
            }
            
            long start = new Date().getTime();
            
            Object object = pjp.proceed();
            
            System.out.println("time aspect 耗时:"+ (new Date().getTime() - start));
            
            System.out.println("time aspect end");
            
            return object;
        }
    
    }
    

    相关文章

      网友评论

          本文标题:filter intercepter aspect

          本文链接:https://www.haomeiwen.com/subject/gxmiultx.html