获取上下文信息

不多说,直接上代码:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.NoSuchMessageException;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 文件名: ContextUtil 项目工程名: 系统通用模块 描述: 通用上下文工具工具 JDK版本:jdk 1.60+
 * 
 */
public class ContextUtil implements ApplicationContextAware, ServletContextAware {

    public static Logger logger = LoggerFactory.getLogger(ContextUtil.class);
    public static ApplicationContext applicationContext;
    public static ServletContext servletContext;
    /** businessSession */
    public static final String BUSINESS_SESSION = "BUSINESS_DATA";

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ContextUtil.applicationContext = applicationContext;
    }

    /**
     * @param servletContext
     *            the servletContext to set
     */
    public void setServletContext(ServletContext servletContext) {
        ContextUtil.servletContext = servletContext;
    }

    // =================bean=================== //

    /**
     * 根据Name取得Bean
     * 
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        Object obj = null;
        if (applicationContext.containsBean(beanName)) {
            try {
                obj = applicationContext.getBean(beanName);
            } catch (BeansException e) {
                logger.warn(e.getMessage());
            }
        } else {
            logger.error("Bean:" + beanName + "不存在.");
        }
        return obj;
    }

    /**
     * 根据Name取得Bean
     * 
     * @param <T>
     * @param beanName
     * @param clazz
     * @return
     */
    public static <T> T getBean(String beanName, Class<T> clazz) {
        T obj = null;
        if (applicationContext.containsBean(beanName)) {
            try {
                obj = (T) applicationContext.getBean(beanName, clazz);
            } catch (BeansException e) {
                logger.warn(e.getMessage());
            }
        } else {
            logger.warn("Bean:" + beanName + "不存在.");
        }
        return obj;
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }

    /**
     * 根据Key取value
     * 
     * @param key
     * @return
     */
    public static String getMsgByKey(String key) {
        String value = "";
        try {
            value = applicationContext.getMessage(key, null, Locale.getDefault());
        } catch (NoSuchMessageException e) {
            logger.warn(e.getMessage());
        } catch (Exception e) {
            logger.warn(e.getMessage());
        }
        return value;
    }

    /**
     * 根据Key取value
     * 
     * @param key
     * @return
     */
    public static Map<String, String> getMapMsgByKey(String key) {
        Map<String, String> bakmap = new HashMap<>();
        try {
            String value = applicationContext.getMessage(key, null, Locale.getDefault());
            String[] datas = value.split(",");
            for (String data : datas) {
                String[] das = data.split("@#");
                bakmap.put(das[0], das[1]);
            }
        } catch (NoSuchMessageException e) {
            logger.warn(e.getMessage());
        } catch (Exception e) {
            logger.warn(e.getMessage());
        }
        return bakmap;
    }

    /**
     * 根据Key取value
     * 
     * @param key
     * @param paramArrayOfObject
     * @return
     */
    public static String getMsgByKey(String key, Object[] paramArrayOfObject) {
        String value = "";
        try {
            value = applicationContext.getMessage(key, paramArrayOfObject, Locale.getDefault());
        } catch (NoSuchMessageException e) {
            logger.warn(e.getMessage());
        } catch (Exception e) {
            logger.warn(e.getMessage());
        }
        return value;
    }

    /**
     * 根据Key取value
     * 
     * @param keys
     * @return
     */
    public static String[] getMsgByKey(String[] keys) {
        String[] values = new String[] {};
        try {
            List<String> list = new ArrayList<String>();
            for (String key : keys) {
                list.add(getMsgByKey(key));
            }
            values = list.toArray(values);
        } catch (NoSuchMessageException e) {
            logger.warn(e.getMessage());
        }
        return values;
    }

    /**
     * 根据Key取value
     * 
     * @param keys
     * @param paramArrayOfObjects
     * @return
     */
    public static String[] getMsgByKey(String[] keys, Object[][] paramArrayOfObjects) {
        String[] values = new String[] {};
        try {
            if (keys == null || paramArrayOfObjects == null) {
                return values;
            } else if (keys.length != paramArrayOfObjects.length) {
                return values;
            }
            List<String> list = new ArrayList<String>();
            for (int i = 0; i < keys.length; i++) {
                list.add(getMsgByKey(keys[i], paramArrayOfObjects[i]));
            }
            values = list.toArray(values);
        } catch (NoSuchMessageException e) {
            logger.warn(e.getMessage());
        }
        return values;
    }

    // =================request=================== //

    /**
     * 获取request
     * 
     * @return
     */
    public static HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        return request;
    }

    /**
     * 获取request中的属性值
     * 
     * @param attName
     *            属性名
     * @return
     */
    public static Object getAttributeFromRequest(String attName) {
        return getRequest().getAttribute(attName);
    }

    /**
     * 获取request中的参数值
     * 
     * @param key
     *            参数Key
     * @return
     */
    public static String getParameterFromRequest(String key) {
        return getRequest().getParameter(key);
    }

    // =================session=================== //

    /**
     * 获取session
     * 
     * @return
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * 获取sessionId
     * 
     * @return
     */
    public static String getSessionId() {
        return getSession().getId();
    }

    /**
     * 获取session创建时间
     * 
     * @return
     */
    public static long getSessionCreationTime() {
        return getSession().getCreationTime();
    }

    /**
     * 获取session最后访问时间
     * 
     * @return
     */
    public static long getSessionLastAccessedTime() {
        return getSession().getLastAccessedTime();
    }

    /**
     * 获取session中的属性值
     * 
     * @param attName
     *            属性名
     * @return
     */
    public static Object getValueFromSession(String attName) {
        return getSession().getAttribute(attName);
    }

    /**
     * 往SystemSession中放值
     * 
     * @param key
     * @param value
     */
    public static void setValueToSystemSession(String key, Object value) {
        getSession().setAttribute(key, value);
    }

    /**
     * 从SystemSession中取值
     * 
     * @param <T>
     * @param key
     * @param clazz
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getValueFromSystemSession(String key, Class<T> clazz) {
        return (T) getValueFromSession(key);
    }

    /**
     * 从SystemSession中取值
     * 
     * @param key
     * @return
     */
    public static Object getValueFromSystemSession(String key) {
        return getValueFromSession(key);
    }

    /**
     * 从SystemSession中移除对象
     * 
     * @param key
     */
    public static void removeFromSystemSession(String key) {
        getSession().removeAttribute(key);
    }

    /**
     * 往BusinessSession中放值
     * 
     * @param key
     * @param value
     */
    @SuppressWarnings("unchecked")
    public static void setValueToBusinessSession(String key, Object value) {
        if (getValueFromSession(BUSINESS_SESSION) == null) {
            Map<String, Object> businessSession = new HashMap<String, Object>();
            businessSession.put(key, value);
            setValueToSystemSession(BUSINESS_SESSION, businessSession);
        } else {
            ((HashMap<String, Object>) getValueFromSession(BUSINESS_SESSION)).put(key, value);
        }
    }

    /**
     * 从BusinessSession中取值
     * 
     * @param <T>
     * @param key
     * @param clazz
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getValueFromBusinessSession(String key, Class<T> clazz) {
        Map<String, Object> sysSession = ((HashMap<String, Object>) getValueFromSession(BUSINESS_SESSION));
        if (sysSession != null) {
            return (T) sysSession.get(key);
        } else {
            return null;
        }
    }

    /**
     * 从BusinessSession中取值
     * 
     * @param key
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Object getValueFromBusinessSession(String key) {
        Map<String, Object> sysSession = ((HashMap<String, Object>) getValueFromSession(BUSINESS_SESSION));
        if (sysSession != null) {
            return sysSession.get(key);
        } else {
            return null;
        }
    }

    /**
     * 从BusinessSession中移除对象
     * 
     * @param key
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Object removeFromBusinessSession(String key) {
        Map<String, Object> sysSession = ((HashMap<String, Object>) getValueFromSession(BUSINESS_SESSION));
        if (sysSession != null) {
            return ((HashMap<String, Object>) getValueFromSession(BUSINESS_SESSION)).remove(key);
        } else {
            return null;
        }
    }

    /**
     * 清空BusinessSession
     */
    @SuppressWarnings("unchecked")
    public static void clearBusinessSession() {
        Map<String, Object> sysSession = ((HashMap<String, Object>) getValueFromSession(BUSINESS_SESSION));
        if (sysSession != null) {
            ((HashMap<String, Object>) getValueFromSession(BUSINESS_SESSION)).clear();
        }
    }

    // =================other=================== //

    /**
     * 取得ContentType
     * 
     * @param ext
     * @return
     */
    public static String getContentTypeByExt(String ext) {
        return getMsgByKey(ext);
    }

    /**
     * 获取绝对路径
     * 
     * @param path
     * @return
     */
    public static String getRealPath(String path) {
        return servletContext.getRealPath(path);
    }

    /**
     * 获取客户端IP地址ַ
     * 
     * @return
     */
    public static String getRemoteAddr() {
        String ip = getRequest().getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = getRequest().getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = getRequest().getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = getRequest().getRemoteAddr();
        }
        return ip;
    }

}
版权声明:如需转载,请注明!PS:如是转载随便,请忽略
原文地址:https://www.cnblogs.com/zwdx/p/7196266.html