cn.itganhuo.app.common.utils.HttpUtil.java Source code

Java tutorial

Introduction

Here is the source code for cn.itganhuo.app.common.utils.HttpUtil.java

Source

/*
 * Copyright 2014-2024 the https://github.com/xiaoxing598/itganhuo.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * This project consists of JAVA private school online learning community group Friends co-creator [QQ group 329232140].
 * JAVA???[QQ329232140];
 * See the list of IT dry technology sharing network [http://www.itganhuo.cn/teams].
 * ????IT[http://www.itganhuo.cn/teams];
 * The author does not guarantee the quality of the project and its stability, reliability, and security does not bear any responsibility.
 * ????????.
 */
package cn.itganhuo.app.common.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import cn.itganhuo.app.common.pool.ConstantPool;
import cn.itganhuo.app.exception.InternalException;

/**
 * <h2>HTTP?????</h2>
 * <dl>
 * <dt>??</dt>
 * <dd></dd>
 * <dt></dt>
 * <dd>??????static???new? </dd>
 * </dl>
 * 
 * @version 0.0.1-SNAPSHOT
 * @author -?
 */
public class HttpUtil {

    private static final Logger logger = LogManager.getLogger(HttpUtil.class);

    private HttpUtil() {
    }

    /**
     * request???
     * 
     * @version 0.0.1-SNAPSHOT
     * @author -?
     * @param httpsession
     * @param name
     *            ??key
     * @return
     */
    public static String getString(HttpServletRequest request, String name) {
        if (StringUtil.hasText(name) && request.getParameter(name) != null)
            return request.getParameter(name).toString().trim();
        else
            return "";
    }

    /**
     * request???
     * 
     * @version 0.0.1-SNAPSHOT
     * @author -?
     * @param request
     * @param name
     * @return
     */
    public static int getInt(HttpServletRequest request, String name) {
        int i = 0;
        if (StringUtil.hasText(name) && request.getParameter(name) != null) {
            String t = request.getParameter(name).toString().trim();
            if (StringUtil.hasText(t)) {
                try {
                    i = Integer.parseInt(t);
                } catch (NumberFormatException e) {
                    i = 0;
                }
            }
        }
        return i;
    }

    /**
     * request???????
     * 
     * @version 0.0.1-SNAPSHOT
     * @author -?
     * @param httpsession
     * @param name
     *            ????
     * @param defaultStr
     *            
     * @return
     */
    public static String getString(HttpServletRequest request, String name, String defaultStr) {
        if (StringUtil.hasText(name) && request.getParameter(name) != null)
            return request.getParameter(name).toString().trim();
        else
            return defaultStr;
    }

    /**
     * Session???
     * 
     * @version 0.0.1-SNAPSHOT
     * @author -?
     * @param httpsession
     * @param name
     *            ??key
     * @return
     */
    public static String getString(HttpSession httpsession, String name) {
        if (StringUtil.hasText(name) && httpsession.getAttribute(name) != null)
            return httpsession.getAttribute(name).toString().trim();
        else
            return "";
    }

    /**
     * Session???????
     * 
     * @version 0.0.1-SNAPSHOT
     * @author -?
     * @param httpsession
     * @param name
     *            ????
     * @param defaultStr
     *            
     * @return
     */
    public static String getString(HttpSession httpsession, String name, String defaultStr) {
        if (StringUtil.hasText(name) && httpsession.getAttribute(name) != null)
            return httpsession.getAttribute(name).toString().trim();
        else
            return defaultStr;
    }

    /**
     * cookie??
     * 
     * @version 0.0.1-SNAPSHOT
     * @author -?
     * @param response
     * @param name
     *            cookie??
     * @param str
     *            ??value
     * @param millisecond
     *            ?
     * @throws ItGanHuoException
     *             ?
     */
    public static void setCookie(HttpServletResponse response, String name, String str, int millisecond) {
        try {
            Cookie cookie = new Cookie(name, URLEncoder.encode(str, "utf-8"));
            cookie.setMaxAge(millisecond);
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            throw new InternalException(logger, e);
        }
    }

    /**
     * cookie??session
     * 
     * @version 0.0.1-SNAPSHOT
     * @author -?
     * @param response
     * @param name
     *            cookie??
     * @param str
     *            ??value
     * @param millisecond
     *            ?
     * @throws ItGanHuoException
     *             ?
     */
    public static void setCookie(HttpServletResponse response, String name, String str) {
        try {
            Cookie cookie = new Cookie(name, URLEncoder.encode(str, "utf-8"));
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            throw new InternalException(logger, e);
        }
    }

    /**
     * cookie???
     * 
     * @version 0.0.1-SNAPSHOT
     * @author -?
     * @param request
     * @param name
     *            cookie??
     * @return ???
     * @throws ItGanHuoException
     */
    public static String getCookie(HttpServletRequest request, String name) {
        try {
            Cookie acookie[] = request.getCookies();
            if (acookie == null)
                return null;
            for (int i = 0; i < acookie.length; i++)
                if (acookie[i] != null && acookie[i].getName().equals(name))
                    return URLDecoder.decode(acookie[i].getValue(), "utf-8");
            return "";
        } catch (UnsupportedEncodingException e) {
            throw new InternalException(logger, e);
        }
    }

    /**
     * cookie??
     * 
     * @version 0.0.1-SNAPSHOT
     * @author -?
     * @param request
     * @return cookiekeyvalue=?
     * @throws ItGanHuoException
     */
    public static String[] getCookie(HttpServletRequest request) {
        try {
            Cookie acookie[] = request.getCookies();
            ArrayList<String> arraylist = new ArrayList<String>();
            if (acookie == null)
                return null;
            for (int i = 0; i < acookie.length; i++) {
                arraylist.add(new StringBuffer().append(acookie[i].getName()).append(" = ")
                        .append(URLDecoder.decode(acookie[i].getValue(), "utf-8")).toString());
            }
            return (String[]) arraylist.toArray(new String[0]);
        } catch (UnsupportedEncodingException e) {
            throw new InternalException(logger, e);
        }
    }

    /**
     * ???cookie
     * 
     * @version 0.0.1-SNAPSHOT
     * @author -?
     * @param response
     * @param request
     * @param name
     *            ?cookie??
     * @throws ItGanHuoException
     */
    public static void delCookie(HttpServletResponse response, HttpServletRequest request, String name) {
        Cookie acookie[] = request.getCookies();
        if (acookie != null) {
            for (int i = 0; i < acookie.length; i++) {
                String s1 = acookie[i].getName();
                if (s1.equals(name)) {
                    acookie[i].setMaxAge(0);
                    response.addCookie(acookie[i]);
                }
            }
        }
    }

    /**
     * Http
     * 
     * @version 0.0.1-SNAPSHOT
     * @author -?
     * @param request
     * @param obj
     *            ??
     * @return
     */
    public static void setValue(HttpServletRequest request, String key, Object obj) {
        if (StringUtil.hasText(key) && obj != null) {
            request.setAttribute(key, obj);
        }
    }

    /**
     * Http?
     * 
     * @version 0.0.1-SNAPSHOT
     * @author -?
     * @param request
     * @param obj
     *            ??
     * @return
     */
    public static void setValue(HttpSession session, String key, Object obj) {
        if (StringUtil.hasText(key) && obj != null) {
            session.setAttribute(key, obj);
        }
    }

    /**
     * ?Shiro?
     * 
     * @version 0.0.1-SNAPSHOT
     * @author -?
     * @param key
     * @param value
     */
    public static void setValue(String key, Object value) {
        Subject current_user = SecurityUtils.getSubject();
        current_user.getSession().setAttribute(key, value);
    }

    /**
     * Shiro??
     * 
     * @version 0.0.1-SNAPSHOT
     * @author -?
     * @param key
     * @return ?
     */
    public static Object getValue(String key) {
        Subject current_user = SecurityUtils.getSubject();
        return current_user.getSession().getAttribute(key);
    }

    /**
     * ??
     * @return
     */
    public static String getToken(HttpSession session) {
        String token = StringUtil.getMD5Shiro(UUID.randomUUID().toString());
        HttpUtil.setValue(session, ConstantPool.SESSION_TOKEN, token);
        return token;
    }

}