Pārlūkot izejas kodu

打卡管理-重复打卡拦截器配置,多次post请求重写ServletRequest

ZhangWenQiang 5 gadi atpakaļ
vecāks
revīzija
8a4ed778c2

+ 63 - 4
happy-job-base-common/src/main/java/com/jeeplus/common/utils/HttpRequestUtils.java

@@ -11,13 +11,72 @@ import java.util.Map;
 /**
  * @Author: zwq
  * @Date: Create in 2020/9/21 10:19
- * @Description: 取httprequest请求参数工具类
+ * @Description: 取httprequest请求参数工具类
  */
 public class HttpRequestUtils {
 
-    public static HashMap<String, String> findRequestMap(HttpServletRequest request) {
+    /**
+     * 多次request请求参数获取
+     * 针对POST方法的参数是存储在输入流中,只能读一次,不能多次读取。
+     * 重写相关ServletRequest方法,实现多次读取的能力
+     *
+     * @param request
+     * @return
+     * @throws IOException
+     */
+    public static HashMap<String, String> getMultiRequestMap(WrappedHttpServletRequest request) throws IOException {
         HashMap<String, String> requestMap = new HashMap<String, String>();
-        // Map requestParams = request.getParameterMap();
+
+        if (request.getMethod().equals("GET")) {
+            Map requestParams = request.getParameterMap();
+            for (Iterator iter = requestParams.keySet().iterator(); iter
+                    .hasNext(); ) {
+                String name = (String) iter.next();
+                String[] values = (String[]) requestParams.get(name);
+                String valueStr = "";
+                for (int i = 0; i < values.length; i++) {
+                    valueStr = (i == values.length - 1) ? valueStr + values[i]
+                            : valueStr + values[i] + ",";
+                }
+                requestMap.put(name, valueStr);
+            }
+        } else {
+            String jsonString = null;
+            try {
+                jsonString = request.getRequestParams();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+            if (jsonString.contains("&")) {
+                String[] strs = jsonString.split("&");
+                for (int i = 0; i < strs.length; i++) {
+                    String json = strs[i];
+                    String[] strs1 = json.split("=");
+                    if (strs1.length == 1) {
+                        requestMap.put(strs1[0].trim(), "");
+                    } else {
+                        requestMap.put(strs1[0].trim(), strs1[1].trim());
+                    }
+                }
+            } else {
+                JSONObject jsonObject = JSONObject.fromObject(jsonString);
+                Iterator<String> keys = jsonObject.keys();// 定义迭代器
+                String key = null;
+                String value = null;
+                while (keys.hasNext()) {
+                    key = keys.next().toString();
+                    value = jsonObject.get(key).toString();
+
+                    requestMap.put(key.trim(), value.trim());
+                }
+            }
+        }
+        return requestMap;
+    }
+
+    public static HashMap<String, String> getRequestMap(HttpServletRequest request) {
+        HashMap<String, String> requestMap = new HashMap<String, String>();
+
         if (request.getMethod().equals("GET")) {
             Map requestParams = request.getParameterMap();
             for (Iterator iter = requestParams.keySet().iterator(); iter
@@ -70,7 +129,6 @@ public class HttpRequestUtils {
         return requestMap;
     }
 
-
     /***
      * 获取 request 中 json 字符串的内容
      *
@@ -119,6 +177,7 @@ public class HttpRequestUtils {
             }
             i += readlen;
         }
+
         return buffer;
     }
 

+ 88 - 0
happy-job-base-common/src/main/java/com/jeeplus/common/utils/WrappedHttpServletRequest.java

@@ -0,0 +1,88 @@
+package com.jeeplus.common.utils;
+
+import org.apache.commons.io.IOUtils;
+
+import javax.servlet.ReadListener;
+import javax.servlet.ServletInputStream;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletRequestWrapper;
+import java.io.*;
+
+/**
+ * @Author: zwq
+ * @Date: Create in 2020/9/21 11:25
+ * @Description:
+ */
+public class WrappedHttpServletRequest extends HttpServletRequestWrapper {
+
+    private byte[] bytes;
+    private WrappedServletInputStream wrappedServletInputStream;
+
+    public WrappedHttpServletRequest(HttpServletRequest request) throws IOException {
+        super(request);
+        // 读取输入流里的请求参数,并保存到bytes里
+        bytes = IOUtils.toByteArray(request.getInputStream());
+        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
+        this.wrappedServletInputStream = new WrappedServletInputStream(byteArrayInputStream);
+        //把post参数重新写入请求流
+        reWriteInputStream();
+
+    }
+
+    /**
+     * 把参数重新写进请求里
+     */
+    public void reWriteInputStream() {
+        wrappedServletInputStream.setStream(new ByteArrayInputStream(bytes != null ? bytes : new byte[0]));
+    }
+
+    @Override
+    public ServletInputStream getInputStream() throws IOException {
+        return wrappedServletInputStream;
+    }
+
+    @Override
+    public BufferedReader getReader() throws IOException {
+        return new BufferedReader(new InputStreamReader(wrappedServletInputStream));
+    }
+
+    /**
+     * 获取post参数,可以自己再转为相应格式
+     */
+    public String getRequestParams() throws IOException {
+        return new String(bytes, this.getCharacterEncoding());
+    }
+
+    private class WrappedServletInputStream extends ServletInputStream {
+
+        public void setStream(InputStream stream) {
+            this.stream = stream;
+        }
+
+        private InputStream stream;
+
+        public WrappedServletInputStream(InputStream stream) {
+            this.stream = stream;
+        }
+
+        @Override
+        public int read() throws IOException {
+            return stream.read();
+        }
+
+        @Override
+        public boolean isFinished() {
+            return true;
+        }
+
+        @Override
+        public boolean isReady() {
+            return true;
+        }
+
+        @Override
+        public void setReadListener(ReadListener readListener) {
+
+        }
+    }
+}

+ 8 - 3
happy-job-module-hpjob/src/main/java/com/jeeplus/modules/sys/aspect/LimitSubmitAspect.java

@@ -5,6 +5,7 @@ import com.jeeplus.common.exception.HappyBootException;
 import com.jeeplus.common.utils.CacheUtils;
 import com.jeeplus.common.utils.HttpRequestUtils;
 import com.jeeplus.common.utils.SpringContextUtils;
+import com.jeeplus.common.utils.WrappedHttpServletRequest;
 import com.jeeplus.modules.api.sys.BaseAppController;
 import org.aspectj.lang.ProceedingJoinPoint;
 import org.aspectj.lang.annotation.Around;
@@ -51,9 +52,12 @@ public class LimitSubmitAspect {
 
     @Around("pointcut()")
     public Object handleSubmit(ProceedingJoinPoint joinPoint) throws Throwable {
+        Object[] args = joinPoint.getArgs();
         //获取用户token
-        HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
-        Map<String, String> requestMap = HttpRequestUtils.findRequestMap(request);
+        HttpServletRequest request = (HttpServletRequest) args[0];
+        //HttpServletRequestWrapper类,重写相关ServletRequest方法
+        WrappedHttpServletRequest requestWrapper = new WrappedHttpServletRequest(request);
+        Map<String, String> requestMap = HttpRequestUtils.getMultiRequestMap(requestWrapper);
         logger.info("param,{}", requestMap);
         String userToken = requestMap.get("user_token");
         //获取切面方法
@@ -84,7 +88,8 @@ public class LimitSubmitAspect {
             CacheUtils.put(APP_USER, key, String.valueOf(now));
         }
         try {
-            Object proceed = joinPoint.proceed();
+            args[0] = requestWrapper;
+            Object proceed = joinPoint.proceed(args);
             return proceed;
         } catch (Throwable e) {
             logger.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(),