国寿i动项目经验之(拦截器Interceptors技术):

  由于Springcloud框架是对Springmvc 进行的二次封装,可以采用面向切面的方式进行前端请求拦截,具体功能逻辑如下:

  

  WebMvcConfigurer.java

  

package com.sinosoft.config;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;import java.util.ArrayList;
import java.util.List;@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {private static final Logger LOGGER = LoggerFactory.getLogger(WebMvcConfigurer.class);/*** 添加拦截器 目的是拦截前端过来的请求** @param registry*/public void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new RequestLog()).addPathPatterns("/**");super.addInterceptors(registry);}/*** 初始化过滤器*/@Beanpublic FilterRegistrationBean filterRegistrationBean() {FilterRegistrationBean registrationBean = new FilterRegistrationBean();MyFilter httpBasicFilter = new MyFilter();registrationBean.setFilter(httpBasicFilter);List<String> urlPatterns = new ArrayList<String>();urlPatterns.add("*");registrationBean.setUrlPatterns(urlPatterns);return registrationBean;}/*** 解决前端跨域请求* <p>* 简单跨域就是GET,HEAD和POST请求,但是POST请求的"Content-Type"只能是application/x-www-form-urlencoded, multipart/form-data 或 text/plain* <p>* 反之,就是非简单跨域,此跨域有一个预检机制,说直白点,就是会发两次请求,一次OPTIONS请求,一次真正的请求** @return*/@Beanpublic CorsFilter corsFilter() {LOGGER.info("开启CorsFilter,解决前后端分离模式接口交互跨域问题");final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();final CorsConfiguration corsConfiguration = new CorsConfiguration();corsConfiguration.setAllowCredentials(true);// 允许cookies跨域corsConfiguration.addAllowedOrigin("*");// #允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的OrigincorsConfiguration.addAllowedHeader("*");// #允许访问的头信息,*表示全部corsConfiguration.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了corsConfiguration.addAllowedMethod("*");//允许所有的请求方式urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);return new CorsFilter(urlBasedCorsConfigurationSource);}
}

LogRecordAspect.java
package com.sinosoft.config;import com.sinosoft.dto.common.RequestInfo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;/*** Created by zh on 03/29/17.*/
@Aspect   //定义一个切面
@Configuration
public class LogRecordAspect {/*** 日志打印*/private static final Logger LOGGER = LoggerFactory.getLogger(LogRecordAspect.class);/*** 定义切点Pointcut* 监控请求对应controller过来接口*/@Pointcut("execution(* com.sinosoft.controller.*Controller.*(..))")public void excudeService() {}@Around("excudeService()")public Object doAround(ProceedingJoinPoint pjp) throws Throwable {LOGGER.info("监控前端请求management应用模块过来的接口...");HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();String url = request.getRequestURL().toString();//获取接口请求详细路径String method = request.getMethod();            //获取接口请求方法String uri = request.getRequestURI();           //获取接口请求路径String queryString = request.getQueryString();  //获取接口请求参数Object[] args = pjp.getArgs();try {for (int i = 0; i < args.length; i++) {if (args[i] instanceof RequestInfo<?>) {RequestInfo<?> r = (RequestInfo<?>) args[i];LOGGER.info("请求开始, 各个参数, url: {}, method: {}, uri: {}, params: {}", url, method, uri, r.toString());} else {LOGGER.info("请求开始, 各个参数, url: {}, method: {}, uri: {}, params: {}", url, method, uri, args[i]);}}} catch (Exception e) {LOGGER.info("请求开始, 各个参数, url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString);}// result的值就是被拦截方法的返回值Object result = pjp.proceed();//LOGGER.info("请求结束,Controller的返回值是 " + result);return result;}}

RequestLog.java
package com.sinosoft.config;import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.time.Instant;public class RequestLog extends HandlerInterceptorAdapter {/*** 前置检查*/@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {String ip = request.getRemoteAddr();Instant startTime = Instant.now();request.setAttribute("logrequestStartTime", startTime);HandlerMethod handlerMethod = (HandlerMethod) handler;// 获取用户tokenMethod method = handlerMethod.getMethod();System.out.println("用户:"+ip+",访问目标:"+method.getDeclaringClass().getName() + "." + method.getName());return true;}// controller处理完成public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {HandlerMethod handlerMethod = (HandlerMethod) handler;Method method = handlerMethod.getMethod();Instant startTime = (Instant) request.getAttribute("logrequestStartTime");Instant endTime = Instant.now();long executeTime = endTime.toEpochMilli()- startTime.toEpochMilli();// log itif (executeTime > 1000) {System.out.println("[" + method.getDeclaringClass().getName() + "." + method.getName() + "] 执行耗时 : "+ executeTime + "ms");} else {System.out.println("[" + method.getDeclaringClass().getSimpleName() + "." + method.getName() + "] 执行耗时 : "+ executeTime + "ms");}}
}

 

  

转载于:https://www.cnblogs.com/xushuyi/articles/6979591.html

SpringCloud(8)—— 国寿i动项目经验之(拦截器Interceptors技术)相关推荐

  1. SpringCloud(9)—— 国寿i动项目经验之(Redis缓存技术)

    国寿i动项目经验之(Redis缓存技术): 首先需要启用redis对应的jar依赖: <dependency><groupId>org.springframework.boot ...

  2. SpringCloud(7)—— 国寿i动项目经验之(过滤器Filter技术(请求体二次解密处理技术))...

    过滤器Filter技术(请求体二次解密处理技术): 对前端App请求进行过滤,在过滤中可以对前端请求体(body)进行二次处理,比如:前端请求的body为加密串.那么就可以在过滤器中对body加密串进 ...

  3. SpringCloud(5)—— 国寿i动项目经验

    国寿i动项目经验(1) 201703初 客户提出构建国寿i动项目,开始第一次尝试解除spring boot.及spring cloud 架构,初始一点都不熟悉这种对springmvc进行二次封装的架构 ...

  4. SpringCloud(10)—— 国寿i动项目经验之(解决前后端跨域请求技术)

    国寿i动项目经验之(解决前后端跨域请求技术): 由于网段原因,导致前端js请求后端服务接口出现跨域,没法实现正常的请求,所以需要对请求进行跨域处理 引入jar: <!-- 解决前后端接口交互跨域 ...

  5. 【项目经验】拦截器拦截入参出参

    文章目录 拦截器拦截入参出参 入参 出参 拦截器拦截入参出参 入参 @Overridepublic boolean preHandle(HttpServletRequest request, Http ...

  6. Springboot项目Aop、拦截器、过滤器横向对比

    前言 伟人曾经说过,没有调查就没有发言权(好像是伟人说的,不管谁说的,这句话是正确的),有些东西看着简单,张口就来,但很有可能是错的.我个人的经验是,aop.过滤器.拦截器的实现方式很简单,一学就会, ...

  7. ssm项目中使用拦截器加上不生效解决方案

    ssm项目中使用拦截器加上不生效解决方案 参考文章: (1)ssm项目中使用拦截器加上不生效解决方案 (2)https://www.cnblogs.com/xiufengchen/p/11205283 ...

  8. 在SpringBoot项目中整合拦截器

    拦截器在Web系统中非常常见,对于某些全局统一的操作,我们可以把它提取到拦截器中实现.总结起来,拦截器大致有以下几种使用场景: 1.权限检查:如登录检测,进入处理程序检测用户是否登录,如果没有,则直接 ...

  9. Spring Boot项目设置权限拦截器和过滤器

    参考博文:https://blog.csdn.net/qq_30745307/article/details/80974407 目录 过滤器 Filter 作用 生命周期 示例代码 拦截器 Inter ...

最新文章

  1. java 移动页面中的图片上传_移动端图片操作——上传
  2. load balancer 配置参考
  3. pycharm + python36 + opencv + opencv_contrib库的安装
  4. SAP License:SAP应用随想
  5. python导入模块的方式错误的是,导入模块时的错误处理
  6. C Primer Plus 第13章 文件输入/输出 13.11 编程练习答案
  7. java速成----一篇博文搞定基础
  8. Linux串口调试工具
  9. 高等数学张宇18讲 第四讲 一元函数微分学的几何应用
  10. cocos入门8:动画系统
  11. qq华夏服务器状态,最国产!QQ华夏199组服务器皆“国名”
  12. RT-Thread学习笔记【ADC与DAC设备】
  13. 服务器维护灵魂兽刷新吗,抓灵魂兽的各种辛酸,魔兽世界猎人当年抓灵魂兽用过的黑科技漫谈...
  14. python 椭圆检测_使用OpenCV和Python检测触摸/重叠圆/椭圆
  15. ginapi服务器性能,基于gin web框架搭建RESTful API服务
  16. r语言股票接口如何获取数据?
  17. Pythonshellcode编码+混淆免杀
  18. mysql查询所有分类前三的数据
  19. OOD, OOA和OOP
  20. 2021年消防工程师证报考条件是什么?

热门文章

  1. NSCameraUsageDescription
  2. Windows10神州网信版的USB故障处理(设备描述符请求失败)
  3. 计算机为了未来作文,未来的计算机作文三篇
  4. 2023最新拼多多助力工具网页版源码+可引流和获取分佣
  5. 花朵数c语言算法,21位花朵数(详解)
  6. python简易英文字典_Python简单有道字典,python,简易,词典
  7. 第十三届蓝桥杯(web组),第五题【页面布局】制作网站首页
  8. C语言 题目 1728: 字符串的查找删除
  9. c语言中-1%3=,c语言数据类型.ppt
  10. Fiddler如何修改请求