13693261870
2024-09-12 b5326f8d497a6f6e97a487cb9c565fdae1dc4790
src/main/java/com/se/simu/helper/WebHelper.java
@@ -1,24 +1,20 @@
package com.se.simu.helper;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
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.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.*;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
/**
@@ -29,15 +25,29 @@
 */
@Slf4j
public class WebHelper {
    public final static String POINT = ".";
    private final static String COMMA = ",";
    private final static String UNKNOWN = "unknown";
    public final static String TOKEN_KEY = "token";
    public static boolean isWin() {
        String osName = System.getProperty("os.name");
    public final static String TOKEN_COOKIE_KEY = "token";
        return osName.startsWith("Windows");
    }
    public final static int COOKIE_MAX_AGE = 4 * 60 * 60;
    /**
     * 格式化日期
     */
    public final static SimpleDateFormat YMDHMS = new SimpleDateFormat("yyyyMMddHHmmss");
    /**
     * 字符串,是否为空null和空格
     */
    public static boolean isEmpty(String str) {
        return null == str || "".equals(str.trim());
    }
    /**
     * 获取GUID
@@ -48,8 +58,6 @@
    /**
     * 获取主机IP
     *
     * @return
     */
    public static String getHostIp() {
        try {
@@ -113,131 +121,6 @@
    }
    /**
     * 获取当前时间指定分钟数后的Timestamp
     */
    public static Timestamp getTimestamp(int min) {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.MINUTE, min);
        return new Timestamp(now.getTimeInMillis());
    }
    /**
     * 从Cookie中获取token
     */
    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 TOKEN_COOKIE_KEY:
                    return cookie.getValue();
                default:
                    break;
            }
        }
        return null;
    }
    /**
     * 向Cookie中添加token
     */
    public static void saveToken2Cookie(String token, HttpServletRequest request, HttpServletResponse response) {
        // 先删除
        deleteCookies(request, response);
        // 再保存
        saveCookie(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(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);
                }
            }
        }
    }
    /**
     * 删除所有Cookie
     */
    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);
            }
        }
    }
    /**
     * 根据键获取Cookie值
     */
    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.从url参数中,获取token
        String token = request.getParameter(TOKEN_KEY);
        // 2.为空,则从header里获取
        if (token == null) {
            token = request.getHeader(TOKEN_KEY);
        }
        // 3.还为空,则从cookie里获取
        if (token == null) {
            token = getTokenFromCookie(request);
        }
        return token;
    }
    /**
     * 获取Request
     */
    public static HttpServletRequest getRequest() {
@@ -256,20 +139,25 @@
    }
    /**
     * 获取Session
     * 输出JSON至页面
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    public static boolean writeJson2Page(HttpServletResponse res, HttpStatus status, Object obj) {
        res.setStatus(status.value());
        return writeStr2Page(res, JSON.toJSONString(obj));
    }
    /**
     * 获取真实路径
     * 输出JSON至页面
     */
    public static String getRealPath(String path) {
        HttpServletRequest req = getRequest();
        ServletContext ctx = req.getSession().getServletContext();
    public static boolean writeJson2Page(HttpServletResponse res, HttpStatus status, String str) {
        res.setStatus(status.value());
        return ctx.getRealPath("/" + path);
        Map<String, Object> map = new HashMap(2);
        map.put("code", status.value() >= 400 ? -1 : 0);
        map.put("msg", str);
        return writeStr2Page(res, JSON.toJSONString(map));
    }
    /**
@@ -304,6 +192,40 @@
    }
    /**
     * 输出字节数组
     */
    public static void writeBytes(byte[] bytes, HttpServletResponse res) throws IOException {
        res.setContentType("application/octet-stream");
        if (null == bytes) {
            res.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        OutputStream os = res.getOutputStream();
        os.write(bytes, 0, bytes.length);
        os.close();
    }
    /**
     * 输出Png文件
     */
    public static void writePng(String filePath, HttpServletResponse res) throws IOException {
        File file = new File(filePath);
        if (!file.exists() || file.isDirectory()) {
            res.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        String fileName = URLEncoder.encode(filePath, "UTF-8").replace("+", "%20");
        res.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);
        res.setCharacterEncoding("UTF-8");
        res.setContentType("image/png");
        writeFile(filePath, res);
    }
    /**
     * 获取随机整数
     */
    public static int getRandomInt(int min, int max) {
@@ -326,8 +248,8 @@
     * @throws Exception 异常
     */
    public static void download(String file, String fileName, boolean inline, HttpServletResponse res) throws Exception {
        if (StringHelper.isEmpty(fileName)) {
            fileName = StringHelper.YMDHMS2_FORMAT.format(new Date());
        if (isEmpty(fileName)) {
            fileName = YMDHMS.format(new Date());
        }
        fileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
        String dispose = inline ? "inline" : "attachment";
@@ -338,10 +260,17 @@
        res.setCharacterEncoding("UTF-8");
        // 通过response对象设置响应数据格式(如:"text/plain; charset=utf-8")
        String ext = FileHelper.getExtension(file);
        String mime = FileHelper.getMime(ext);
        String ext = getExtension(file);
        String mime = getMime(ext);
        res.setContentType(mime);
        writeFile(file, res);
    }
    /**
     * 写文件
     */
    private static void writeFile(String file, HttpServletResponse res) throws IOException {
        // 通过response对象,获取到输出流
        ServletOutputStream outputStream = res.getOutputStream();
        // 定义输入流,通过输入流读取文件内容
@@ -361,75 +290,105 @@
    }
    /**
     * 执行命令
     *
     * @param cmd 命令
     * 获取文件扩展名
     */
    public static void exec(String cmd) {
        try {
            Runtime.getRuntime().exec(cmd);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
    public static String getExtension(String fileName) {
        if (isEmpty(fileName)) {
            return "";
        }
        int idx = fileName.lastIndexOf(POINT);
        if (idx == -1) {
            return "";
        }
        return fileName.substring(idx).toLowerCase();
    }
    /**
     * 执行命令
     *
     * @param cmd 命令
     * 获取多用途互联网邮件扩展类型
     */
    public static String exec2(String cmd) {
        try {
            StringBuilder sb = new StringBuilder();
            Process process = Runtime.getRuntime().exec(cmd);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            reader.close();
            return sb.toString();
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            return null;
    public static String getMime(String ext) {
        switch (ext) {
            // 图片
            case ".tif":
            case ".tiff":
                return "image/tiff";
            case ".img":
                return "application/x-img";
            case ".gif":
                return "image/gif";
            case ".jpg":
            case ".jpeg":
                return "image/jpeg";
            case ".png":
                return "image/png";
            // 音/视频
            case ".mp3":
                return "audio/mp3";
            case ".mp4":
                return "video/mpeg4";
            case ".avi":
                return "video/avi";
            case ".mpg":
            case ".mpeg":
                return "video/mpg";
            case ".wav":
                return "audio/wav";
            case ".wma":
                return "audio/x-ms-wma";
            case ".swf":
                return "application/x-shockwave-flash";
            case ".wmv":
                return "video/x-ms-wmv";
            case ".rm":
                return "application/vnd.rn-realmedia";
            case ".rmvb":
                return "application/vnd.rn-realmedia-vbr";
            // 网页
            case ".js":
                return "application/x-javascript";
            case ".css":
                return "text/css";
            case ".asp":
                return "text/asp";
            case ".mht":
                return "message/rfc822";
            case ".jsp":
            case ".htm":
            case ".html":
            case ".xhtml":
                return "text/html";
            case ".xml":
            case ".svg":
                return "text/xml";
            // 文件
            case ".txt":
                return "text/plain";
            case ".dbf":
                return "application/x-dbf";
            case ".mdb":
                return "application/msaccess";
            case ".pdf":
                return "application/pdf";
            case ".ppt":
            case ".pptx":
                return "application/x-ppt";
            case ".doc":
            case ".docx":
                return "application/msword";
            case ".xls":
            case ".xlsx":
                return "application/vnd.ms-excel";
            case ".dgn":
                return "application/x-dgn";
            case ".dwg":
                return "application/x-dwg";
            case ".ext":
                return "application/x-msdownload";
            // 默认
            default:
                return "application/octet-stream";
        }
    }
    /**
     * 获取请求的参数值
     *
     * @param req 请求
     * @param key 参数名
     * @return 参数值
     */
    public static String getReqParamVal(HttpServletRequest req, String key) {
        Map<String, String[]> maps = req.getParameterMap();
        for (Map.Entry<String, String[]> entry : maps.entrySet()) {
            if (entry.getKey().equalsIgnoreCase(key)) {
                return null == entry.getValue() || 0 == entry.getValue().length ? null : entry.getValue()[0];
            }
        }
        return null;
    }
    /**
     * 获取请求的参数值
     *
     * @param req 请求
     * @param key 参数名
     * @return 参数值
     */
    public static String[] getReqParamVals(HttpServletRequest req, String key) {
        Map<String, String[]> maps = req.getParameterMap();
        for (Map.Entry<String, String[]> entry : maps.entrySet()) {
            if (entry.getKey().equalsIgnoreCase(key)) {
                return entry.getValue();
            }
        }
        return null;
    }
}