月球大数据地理空间分析展示平台-【后端】-月球后台服务
1
13693261870
2024-11-13 a088987e7ab7005db1bb1da61dfc0cf420e02d78
src/main/java/com/moon/server/helper/WebHelper.java
@@ -22,10 +22,7 @@
import java.sql.Timestamp;
import java.util.*;
/**
 * Web帮助类
 * @author WWW
 */
@SuppressWarnings("ALL")
public class WebHelper {
    private final static String UNKNOWN = "unknown";
@@ -33,25 +30,16 @@
    private final static Log log = LogFactory.getLog(WebHelper.class);
    /**
     * 保留小数位
     */
    public static double round(double val, double size) {
        double power = Math.pow(10.0, size);
        return Math.round(val * power) / power;
    }
    /**
     * 获取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)) {
@@ -94,16 +82,10 @@
        return ip;
    }
    /**
     * 获取当前时间的Timestamp
     */
    public static Timestamp getCurrentTimestamp() {
        return new Timestamp(System.currentTimeMillis());
    }
    /**
     * 获取当前时间指定分钟数后的Timestamp
     */
    public static Timestamp getTimestamp(int min) {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.MINUTE, min);
@@ -111,9 +93,6 @@
        return new Timestamp(now.getTimeInMillis());
    }
    /**
     * 从Cookie中获取token
     */
    public static String getTokenFromCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length == 0) {
@@ -132,23 +111,14 @@
        return null;
    }
    /**
     * 向Cookie中添加token
     */
    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("/");
@@ -158,9 +128,6 @@
        response.addCookie(cookie);
    }
    /**
     * 删除cookie中的值
     */
    public static void deleteCookie(String cookieKey, HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
@@ -174,9 +141,6 @@
        }
    }
    /**
     * 删除所有Cookie
     */
    public static void deleteCookies(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
@@ -188,9 +152,6 @@
        }
    }
    /**
     * 根据键获取Cookie值
     */
    public static String getCookieByKey(String key, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length == 0) {
@@ -206,19 +167,13 @@
        return null;
    }
    /**
     * 获取Token
     */
    public static String getToken(HttpServletRequest request) {
        // 1.从url参数中,获取token
        String token = request.getParameter(StaticData.TOKEN_KEY);
        // 2.为空,则从header里获取
        if (token == null) {
            token = request.getHeader(StaticData.TOKEN_KEY);
        }
        // 3.还为空,则从cookie里获取
        if (token == null) {
            token = getTokenFromCookie(request);
        }
@@ -226,34 +181,22 @@
        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();
@@ -261,9 +204,6 @@
        return ctx.getRealPath("/" + path);
    }
    /**
     * 输出str至前端
     */
    public static boolean writeStr2Page(HttpServletResponse res, String str) {
        try {
            res.setContentType("application/json;charset=UTF-8");
@@ -283,50 +223,27 @@
        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());
@@ -334,39 +251,27 @@
        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 {
            Process process = Runtime.getRuntime().exec(cmd);
@@ -376,13 +281,6 @@
        }
    }
    /**
     * 获取请求的参数值
     *
     * @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()) {
@@ -394,13 +292,6 @@
        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()) {