管道基础大数据平台系统开发-【后端】-Server
13693261870
2024-03-25 b6b0cb226fcf184525ee7b36af3a09471e9c0057
src/main/java/com/lf/server/helper/WebHelper.java
@@ -1,20 +1,25 @@
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.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.IOException;
import java.io.PrintWriter;
import java.io.*;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.UUID;
import java.util.*;
/**
 * Web帮助类
@@ -24,6 +29,8 @@
    private final static String UNKNOWN = "unknown";
    private final static String COMMA = ",";
    private final static Log log = LogFactory.getLog(WebHelper.class);
    /**
     * 获取GUID
@@ -245,20 +252,176 @@
    }
    /**
     * 输出json数据到前端
     * 输出str至前端
     */
    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);
    public static boolean writeStr2Page(HttpServletResponse res, String str) {
        try {
            res.setContentType("application/json;charset=UTF-8");
            res.setHeader("Cache-Control", "no-cache");
            res.setHeader("Pragma", "No-cache");
            res.setDateHeader("Expires", 0);
        PrintWriter out = response.getWriter();
        out.print(jsonPack);
            PrintWriter out = res.getWriter();
            out.print(str);
        out.flush();
        out.close();
            out.flush();
            out.close();
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        return false;
    }
    /**
     * 输出json至前端
     */
    public static void writeJson2Page(HttpServletResponse res, String str) {
        String json = JSON.toJSONString(new ResponseMsg<>(HttpStatus.ERROR, str));
        writeStr2Page(res, json);
    }
    /**
     * 获取错误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) {
        WebHelper.writeStr2Page(res, WebHelper.getErrJson(status, info));
    }
    /**
     * 获取随机整数
     */
    public static int getRandomInt(int min, int max) {
        return new Random().nextInt(max) % (max - min + 1) + min;
    }
    /**
     * 下载文件
     */
    public static void download(String file, String fileName, HttpServletResponse res) throws Exception {
        download(file, fileName, false, res);
    }
    /**
     * 下载文件
     *
     * @param file     文件
     * @param fileName 文件名
     * @param res      响应
     * @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());
        }
        fileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
        String dispose = inline ? "inline" : "attachment";
        // 设置响应头中文件的下载方式为附件方式,以及设置文件名
        res.setHeader("Content-Disposition", dispose + "; filename*=UTF-8''" + fileName);
        // 设置响应头的编码格式为 UTF-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();
        }
        // 关闭资源
        fileInputStream.close();
        outputStream.close();
    }
    /**
     * 执行命令
     *
     * @param cmd 命令
     */
    public static void exec(String cmd) {
        try {
            Runtime.getRuntime().exec(cmd);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }
    /**
     * 执行命令
     *
     * @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;
        }
    }
    /**
     * 获取请求的参数值
     *
     * @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;
    }
}