PageProcessAspect.java 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. package com.java110.front.aop;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.java110.core.context.IPageData;
  4. import com.java110.core.context.PageData;
  5. import com.java110.utils.constant.CommonConstant;
  6. import com.java110.utils.exception.FilterException;
  7. import com.java110.utils.util.StringUtil;
  8. import org.aspectj.lang.JoinPoint;
  9. import org.aspectj.lang.ProceedingJoinPoint;
  10. import org.aspectj.lang.annotation.After;
  11. import org.aspectj.lang.annotation.AfterReturning;
  12. import org.aspectj.lang.annotation.AfterThrowing;
  13. import org.aspectj.lang.annotation.Around;
  14. import org.aspectj.lang.annotation.Aspect;
  15. import org.aspectj.lang.annotation.Before;
  16. import org.aspectj.lang.annotation.Pointcut;
  17. import org.slf4j.Logger;
  18. import org.slf4j.LoggerFactory;
  19. import org.springframework.http.HttpMethod;
  20. import org.springframework.http.HttpStatus;
  21. import org.springframework.http.ResponseEntity;
  22. import org.springframework.stereotype.Component;
  23. import org.springframework.web.context.request.RequestContextHolder;
  24. import org.springframework.web.context.request.ServletRequestAttributes;
  25. import javax.servlet.http.Cookie;
  26. import javax.servlet.http.HttpServletRequest;
  27. import javax.servlet.http.HttpServletResponse;
  28. import java.io.BufferedReader;
  29. import java.io.IOException;
  30. import java.io.InputStream;
  31. import java.io.InputStreamReader;
  32. import java.util.Map;
  33. /**
  34. * 数据初始化
  35. * Created by wuxw on 2018/5/2.
  36. */
  37. @Aspect
  38. @Component
  39. public class PageProcessAspect {
  40. private static Logger logger = LoggerFactory.getLogger(PageProcessAspect.class);
  41. @Pointcut("execution(public * com.java110..*.*Controller.*(..)) || execution(public * com.java110..*.*Rest.*(..))")
  42. public void dataProcess() {
  43. }
  44. /**
  45. * 初始化数据
  46. *
  47. * @param joinPoint
  48. * @throws Throwable
  49. */
  50. @Before("dataProcess()")
  51. public void deBefore(JoinPoint joinPoint) throws Throwable {
  52. // 接收到请求,记录请求内容
  53. ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  54. HttpServletRequest request = attributes.getRequest();
  55. IPageData pd = null;
  56. String reqData = "";
  57. String userId = "";
  58. String userName = "";
  59. String appId = "";
  60. String sessionId = request.getSession().getId();
  61. appId = request.getHeader("APP_ID");
  62. if (StringUtil.isEmpty(appId)) {
  63. appId = request.getHeader("APP-ID");
  64. }
  65. logger.debug("请求头信息:" + request.getHeaderNames());
  66. if ("POST,PUT".contains(request.getMethod())) {
  67. InputStream in = request.getInputStream();
  68. BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  69. //reader.
  70. StringBuffer sb = new StringBuffer();
  71. String str = "";
  72. while ((str = reader.readLine()) != null) {
  73. sb.append(str);
  74. }
  75. reqData = sb.toString();
  76. }
  77. //对 get情况下的参数进行封装
  78. else {
  79. Map<String, String[]> params = request.getParameterMap();
  80. if (params != null && !params.isEmpty()) {
  81. JSONObject paramObj = new JSONObject();
  82. for (String key : params.keySet()) {
  83. if (params.get(key).length > 0) {
  84. String value = "";
  85. for (int paramIndex = 0; paramIndex < params.get(key).length; paramIndex++) {
  86. value = params.get(key)[paramIndex] + ",";
  87. }
  88. value = value.endsWith(",") ? value.substring(0, value.length() - 1) : value;
  89. paramObj.put(key, value);
  90. }
  91. continue;
  92. }
  93. reqData = paramObj.toJSONString();
  94. }
  95. }
  96. // 获取 userId
  97. if (request.getAttribute("claims") != null && request.getAttribute("claims") instanceof Map) {
  98. Map<String, String> userInfo = (Map<String, String>) request.getAttribute("claims");
  99. if (userInfo.containsKey(CommonConstant.LOGIN_USER_ID)) {
  100. userId = userInfo.get(CommonConstant.LOGIN_USER_ID);
  101. userName = userInfo.get(CommonConstant.LOGIN_USER_NAME);
  102. }
  103. }
  104. // 获取组件名称 和方法名称
  105. String url = request.getRequestURL() != null ? request.getRequestURL().toString() : "";
  106. String componentCode = "";
  107. String componentMethod = "";
  108. if (url.contains("callComponent")) { //组件处理
  109. String[] urls = url.split("/");
  110. if (urls.length == 6) {
  111. componentCode = urls[4];
  112. componentMethod = urls[5];
  113. } else {
  114. componentCode = "api";
  115. componentMethod = "callApi";
  116. }
  117. } else if (url.contains("flow")) { //流程处理
  118. String[] urls = url.split("/");
  119. if (urls.length == 5) {
  120. componentCode = urls[4];
  121. }
  122. }
  123. pd = PageData.newInstance().builder(userId, userName, this.getToken(request), reqData, componentCode, componentMethod, url, sessionId, appId);
  124. pd.setMethod(request.getMethod().equals("GET") ? HttpMethod.GET : HttpMethod.POST);
  125. request.setAttribute(CommonConstant.CONTEXT_PAGE_DATA, pd);
  126. }
  127. @AfterReturning(returning = "ret", pointcut = "dataProcess()")
  128. public void doAfterReturning(Object ret) throws Throwable {
  129. // 处理完请求,返回内容
  130. }
  131. //后置异常通知
  132. @AfterThrowing("dataProcess()")
  133. public void throwException(JoinPoint jp) {
  134. }
  135. //后置最终通知,final增强,不管是抛出异常或者正常退出都会执行
  136. @After("dataProcess()")
  137. public void after(JoinPoint jp) throws IOException {
  138. // 接收到请求,记录请求内容
  139. ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  140. HttpServletRequest request = attributes.getRequest();
  141. PageData pd = request.getAttribute(CommonConstant.CONTEXT_PAGE_DATA) != null ? (PageData) request.getAttribute(CommonConstant.CONTEXT_PAGE_DATA) : null;
  142. //保存日志处理
  143. if (pd == null) {
  144. return;
  145. }
  146. //写cookies信息
  147. writeCookieInfo(pd, attributes);
  148. }
  149. //环绕通知,环绕增强,相当于MethodInterceptor
  150. @Around("dataProcess()")
  151. public Object around(ProceedingJoinPoint pjp) {
  152. try {
  153. Object o = pjp.proceed();
  154. return o;
  155. } catch (Throwable e) {
  156. logger.error("执行方法异常", e);
  157. return new ResponseEntity("内部异常" + e.getLocalizedMessage(), HttpStatus.BAD_REQUEST);
  158. }
  159. }
  160. /**
  161. * 获取TOKEN
  162. *
  163. * @param request
  164. * @return
  165. */
  166. private String getToken(HttpServletRequest request) throws FilterException {
  167. String token = "";
  168. if (request.getCookies() == null || request.getCookies().length == 0) {
  169. return token;
  170. }
  171. for (Cookie cookie : request.getCookies()) {
  172. if (CommonConstant.COOKIE_AUTH_TOKEN.equals(cookie.getName())) {
  173. token = cookie.getValue();
  174. }
  175. }
  176. return token;
  177. }
  178. /**
  179. * 写cookie 信息
  180. *
  181. * @param pd 页面封装信息
  182. * @param attributes
  183. * @throws IOException
  184. */
  185. private void writeCookieInfo(IPageData pd, ServletRequestAttributes attributes) throws IOException {
  186. // 这里目前只写到组件级别,如果需要 写成方法级别
  187. if (!StringUtil.isNullOrNone(pd.getToken()) && "login".equals(pd.getComponentCode())) {
  188. HttpServletResponse response = attributes.getResponse();
  189. Cookie cookie = new Cookie(CommonConstant.COOKIE_AUTH_TOKEN, pd.getToken());
  190. cookie.setHttpOnly(true);
  191. cookie.setPath("/");
  192. response.addCookie(cookie);
  193. response.flushBuffer();
  194. }
  195. }
  196. }