From ab849f796bdc17236a95ea5fe5c166fb8f24a75c Mon Sep 17 00:00:00 2001
From: sws <15810472099@163.com>
Date: 星期六, 26 十一月 2022 16:12:02 +0800
Subject: [PATCH] 1

---
 src/main/java/com/lf/server/helper/WebHelper.java |  337 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 337 insertions(+), 0 deletions(-)

diff --git a/src/main/java/com/lf/server/helper/WebHelper.java b/src/main/java/com/lf/server/helper/WebHelper.java
new file mode 100644
index 0000000..8fabfc5
--- /dev/null
+++ b/src/main/java/com/lf/server/helper/WebHelper.java
@@ -0,0 +1,337 @@
+package com.lf.server.helper;
+
+import com.alibaba.fastjson.JSON;
+import com.lf.server.entity.all.HttpStatus;
+import com.lf.server.entity.all.ResponseMsg;
+import com.lf.server.entity.all.SettingData;
+import com.lf.server.entity.all.StaticData;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+
+import javax.servlet.ServletContext;
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.net.URLEncoder;
+import java.sql.Timestamp;
+import java.util.Calendar;
+import java.util.Random;
+import java.util.UUID;
+
+/**
+ * Web甯姪绫�
+ * @author WWW
+ */
+public class WebHelper {
+    private final static String UNKNOWN = "unknown";
+
+    private final static String COMMA = ",";
+
+    /**
+     * 鑾峰彇GUID
+     */
+    public static String getGuid() {
+        return UUID.randomUUID().toString();
+    }
+
+    /**
+     * 鑾峰彇鐢ㄦ埛ip
+     */
+    public static String getIpAddress(HttpServletRequest request) {
+        String ip = request.getHeader("X-Forwarded-For");
+        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
+            ip = request.getHeader("Proxy-Client-IP");
+        }
+        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
+            ip = request.getHeader("WL-Proxy-Client-IP");
+        }
+        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
+            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
+        }
+        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
+            ip = request.getHeader("HTTP_X_FORWARDED");
+        }
+        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
+            ip = request.getHeader("HTTP_X_CLUSTER_CLIENT_IP");
+        }
+        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
+            ip = request.getHeader("HTTP_CLIENT_IP");
+        }
+        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
+            ip = request.getHeader("HTTP_FORWARDED_FOR");
+        }
+        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
+            ip = request.getHeader("HTTP_FORWARDED");
+        }
+        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
+            ip = request.getHeader("HTTP_VIA");
+        }
+        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
+            ip = request.getHeader("REMOTE_ADDR");
+        }
+        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
+            ip = request.getRemoteAddr();
+        }
+        if (ip.contains(COMMA)) {
+            return ip.split(",")[0];
+        }
+
+        return ip;
+    }
+
+    /**
+     * 鑾峰彇褰撳墠鏃堕棿鐨凾imestamp
+     */
+    public static Timestamp getCurrentTimestamp() {
+        return new Timestamp(System.currentTimeMillis());
+    }
+
+    /**
+     * 鑾峰彇褰撳墠鏃堕棿鎸囧畾鍒嗛挓鏁板悗鐨凾imestamp
+     */
+    public static Timestamp getTimestamp(int min) {
+        Calendar now = Calendar.getInstance();
+        now.add(Calendar.MINUTE, min);
+
+        return new Timestamp(now.getTimeInMillis());
+    }
+
+    /**
+     * 浠嶤ookie涓幏鍙杢oken
+     */
+    public static String getTokenFromCookie(HttpServletRequest request) {
+        Cookie[] cookies = request.getCookies();
+        if (cookies == null || cookies.length == 0) {
+            return null;
+        }
+
+        for (Cookie cookie : cookies) {
+            switch (cookie.getName()) {
+                case StaticData.TOKEN_COOKIE_KEY:
+                    return cookie.getValue();
+                default:
+                    break;
+            }
+        }
+
+        return null;
+    }
+
+    /**
+     * 鍚慍ookie涓坊鍔爐oken
+     */
+    public static void saveToken2Cookie(String token, HttpServletRequest request, HttpServletResponse response) {
+        // 鍏堝垹闄�
+        deleteCookies(request, response);
+
+        // 鍐嶄繚瀛�
+        saveCookie(StaticData.TOKEN_COOKIE_KEY, token, response);
+    }
+
+    /**
+     * 淇濆瓨Cookie
+     */
+    public static void saveCookie(String key, String value, HttpServletResponse response) {
+        Cookie cookie = new Cookie(key, value);
+        // 璁剧疆cookie澶辨晥鏃堕棿锛屽崟浣嶄负绉�
+        cookie.setMaxAge(SettingData.COOKIE_MAX_AGE);
+        cookie.setHttpOnly(false);
+        cookie.setPath("/");
+        //cookie.setDomain("*")
+
+        response.setHeader("P3P", "CP=CAO PSA OUR");
+        response.addCookie(cookie);
+    }
+
+    /**
+     * 鍒犻櫎cookie涓殑鍊�
+     */
+    public static void deleteCookie(String cookieKey, HttpServletRequest request, HttpServletResponse response) {
+        Cookie[] cookies = request.getCookies();
+        if (cookies != null && cookies.length > 0) {
+            for (Cookie c : cookies) {
+                if (cookieKey.equalsIgnoreCase(c.getName())) {
+                    c.setMaxAge(0);
+                    c.setPath("/");
+                    response.addCookie(c);
+                }
+            }
+        }
+    }
+
+    /**
+     * 鍒犻櫎鎵�鏈塁ookie
+     */
+    public static void deleteCookies(HttpServletRequest request, HttpServletResponse response) {
+        Cookie[] cookies = request.getCookies();
+        if (cookies != null && cookies.length > 0) {
+            for (Cookie c : cookies) {
+                c.setMaxAge(0);
+                c.setPath("/");
+                response.addCookie(c);
+            }
+        }
+    }
+
+    /**
+     * 鏍规嵁閿幏鍙朇ookie鍊�
+     */
+    public static String getCookieByKey(String key, HttpServletRequest request) {
+        Cookie[] cookies = request.getCookies();
+        if (cookies == null || cookies.length == 0) {
+            return null;
+        }
+
+        for (Cookie c : cookies) {
+            if (key.equals(c.getName())) {
+                return c.getValue();
+            }
+        }
+
+        return null;
+    }
+
+    /**
+     * 鑾峰彇Token
+     */
+    public static String getToken(HttpServletRequest request) {
+        // 1.浠巙rl鍙傛暟涓紝鑾峰彇token
+        String token = request.getParameter(StaticData.TOKEN_KEY);
+
+        // 2.涓虹┖锛屽垯浠巋eader閲岃幏鍙�
+        if (token == null) {
+            token = request.getHeader(StaticData.TOKEN_KEY);
+        }
+
+        // 3.杩樹负绌猴紝鍒欎粠cookie閲岃幏鍙�
+        if (token == null) {
+            token = getTokenFromCookie(request);
+        }
+
+        return token;
+    }
+
+    /**
+     * 鑾峰彇Request
+     */
+    public static HttpServletRequest getRequest() {
+        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
+
+        return servletRequestAttributes.getRequest();
+    }
+
+    /**
+     * 鑾峰彇Response
+     */
+    public static HttpServletResponse getResponse() {
+        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
+
+        return servletRequestAttributes.getResponse();
+    }
+
+    /**
+     * 鑾峰彇Session
+     */
+    public static HttpSession getSession() {
+        return getRequest().getSession();
+    }
+
+    /**
+     * 鑾峰彇鐪熷疄璺緞
+     */
+    public static String getRealPath(String path) {
+        HttpServletRequest req = getRequest();
+        ServletContext ctx = req.getSession().getServletContext();
+
+        return ctx.getRealPath("/" + path);
+    }
+
+    /**
+     * 杈撳嚭json鏁版嵁鍒板墠绔�
+     */
+    public static boolean write2Page(HttpServletResponse response, String jsonPack) throws IOException {
+        response.setContentType("application/json;charset=UTF-8");
+        response.setHeader("Cache-Control", "no-cache");
+        response.setHeader("Pragma", "No-cache");
+        response.setDateHeader("Expires", 0);
+
+        PrintWriter out = response.getWriter();
+        out.print(jsonPack);
+
+        out.flush();
+        out.close();
+
+        return false;
+    }
+
+    /**
+     * 鑾峰彇閿欒JSON
+     */
+    public static String getErrJson(HttpStatus status, String msg) {
+        return JSON.toJSONString(new ResponseMsg<String>(status, msg));
+    }
+
+    /**
+     * 鍐欏搷搴斾俊鎭�
+     */
+    public static void writeInfo(HttpStatus status, String info, HttpServletResponse res) {
+        try {
+            WebHelper.write2Page(res, WebHelper.getErrJson(status, info));
+        } catch (Exception e) {
+            //
+        }
+    }
+
+    /**
+     * 鑾峰彇闅忔満鏁存暟
+     */
+    public static int getRandomInt(int min, int max) {
+        return new Random().nextInt(max) % (max - min + 1) + min;
+    }
+
+    /**
+     * 涓嬭浇鏂囦欢
+     *
+     * @param file     鏂囦欢
+     * @param fileName 鏂囦欢鍚�
+     * @param res      鍝嶅簲
+     * @throws Exception 寮傚父
+     */
+    public static void download(String file, String fileName, HttpServletResponse res) throws Exception {
+        if (StringHelper.isNull(fileName)) {
+            fileName = URLEncoder.encode(FileHelper.getFileName(file), "UTF-8");
+        }
+
+        // 璁剧疆鍝嶅簲澶翠腑鏂囦欢鐨勪笅杞芥柟寮忎负闄勪欢鏂瑰紡锛屼互鍙婅缃枃浠跺悕
+        res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
+        // 璁剧疆鍝嶅簲澶寸殑缂栫爜鏍煎紡涓篣TF-8
+        res.setCharacterEncoding("UTF-8");
+
+        // 閫氳繃response瀵硅薄璁剧疆鍝嶅簲鏁版嵁鏍煎紡(濡傦細"text/plain; charset=utf-8")
+        String ext = FileHelper.getExtension(file);
+        String mime = FileHelper.getMime(ext);
+        res.setContentType(mime);
+
+        // 閫氳繃response瀵硅薄锛岃幏鍙栧埌杈撳嚭娴�
+        ServletOutputStream outputStream = res.getOutputStream();
+        // 瀹氫箟杈撳叆娴侊紝閫氳繃杈撳叆娴佽鍙栨枃浠跺唴瀹�
+        FileInputStream fileInputStream = new FileInputStream(file);
+
+        int len = 0;
+        byte[] bytes = new byte[1024];
+        while ((len = fileInputStream.read(bytes)) != -1) {
+            // 閫氳繃杈撳叆娴佽鍙栨枃浠舵暟鎹紝鐒跺悗閫氳繃涓婅堪鐨勮緭鍑烘祦鍐欏洖娴忚鍣�
+            outputStream.write(bytes, 0, len);
+            outputStream.flush();
+        }
+
+        // 鍏抽棴璧勬簮
+        outputStream.close();
+        fileInputStream.close();
+    }
+}

--
Gitblit v1.9.3