Java工具封装:增强Hutool的SpringUtil工具

EnhanceSpringUtil .java

public class EnhanceSpringUtil extends SpringUtil {

    /**
     * 获取当前请求
     *
     * @return
     */
    public static HttpServletRequest getCurrrentRequest() {
        return Optional.ofNullable((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .map(ServletRequestAttributes::getRequest)
                .orElseThrow(() -> new RuntimeException("非Web应用,请检查"));
    }

    /**
     * 获取当前请求的请求方式
     *
     * @return
     */
    public static String getCurrrentRequestMethod() {
        return getCurrrentRequest().getMethod();
    }

    /**
     * 获取当前请求的会话ID
     * @return
     */
    public static String getCurrentRequestSessionId() {
        return getCurrrentRequest().getSession().getId();
    }

    /**
     * 获取当前响应
     *
     * @return
     */
    public static HttpServletResponse getCurrentResponse() {
        return Optional.ofNullable((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .map(ServletRequestAttributes::getResponse)
                .orElseThrow(() -> new RuntimeException("非Web应用,请检查"));
    }

    /**
     * 获取当前请求表单、url参数
     *
     * @return
     */
    @SneakyThrows
    public static Dict getCurrentRequestParams() {
        HttpServletRequest currrentRequest = getCurrrentRequest();
        Dict params = MapUtil.emptyIfNull(currrentRequest.getParameterMap())
                .entrySet().stream()
                .collect(Collectors.toMap(paramKeyValues -> paramKeyValues.getKey(), paramKeyValues -> paramKeyValues.getValue()[0], (t1, t2) -> t2, () -> Dict.create()));

        // 填充文件上传的参数
        String contentType = getCurrentRequestHeader("Content-Type");
        if (StrUtil.containsAnyIgnoreCase(contentType, "multipart/form-data", "multipart/mixed")) {
            Collection<Part> parts = currrentRequest.getParts();
            Class standardMultipartFileClazz = EnhanceClassUtil.forName("org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile");
            Constructor constructor = ReflectUtil.getConstructor(standardMultipartFileClazz, Part.class, String.class);
            for (Part part : parts) {
                String keyName = part.getName();
                if (!params.containsKey(keyName)) {
                    Object standardMultipartFileBean = constructor.newInstance(part, part.getSubmittedFileName());
                    params.put(keyName, standardMultipartFileBean);
                }
            }
        }


        return params;
    }

    /**
     * 获取当前请求表单、url参数
     *
     * @return
     */
    public static <T> T getCurrentRequestParams(Class<T> resultBeanClazz) {
        return getCurrentRequestParams().toBeanIgnoreCase(resultBeanClazz);
    }

    /**
     * 获取当前请求某个表单、url参数
     *
     * @return
     */
    public static <T> T getCurrentRequestParam(String paramName, Class<T> resultTypeClazz) {
        return getCurrentRequestParams().getByPath(paramName, resultTypeClazz);
    }

    /**
     * 获取当前请求某个表单、url参数
     *
     * @return
     */
    public static String getCurrentRequestParam(String paramName) {
        return getCurrentRequestParams().getByPath(paramName, String.class);
    }

    /**
     * 获取当前请求某个表单、url参数
     *
     * @return
     */
    public static <T, M> M getCurrentRequestParam(Func1<T, M> paramName) {
        String fieldName = LambdaUtil.getFieldName(paramName);
        Class<M> methodResultType = EnhanceLambdaUtil.getMethodResultType(paramName);
        return getCurrentRequestParam(fieldName, methodResultType);
    }


    /**
     * 获取获取当前请求头
     *
     * @return
     */
    public static Dict getCurrentRequestHeaders() {
        HttpServletRequest currrentRequest = getCurrrentRequest();
        Dict headerKeyValues = Dict.create();
        Enumeration<String> headerNames = currrentRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            headerKeyValues.put(headerName, currrentRequest.getHeader(headerName));
            headerKeyValues.put(headerName.toLowerCase(), currrentRequest.getHeader(headerName));
            headerKeyValues.put(headerName.toUpperCase(), currrentRequest.getHeader(headerName));

            List<String> headerNameList = StrUtil.split(headerName, StrUtil.DASHED);
            String dashUpperHeaderName = headerNameList.stream()
                    .map(StrUtil::upperFirst)
                    .collect(Collectors.joining(StrUtil.DASHED));
            String dashLowerHeaderName = headerNameList.stream()
                    .map(StrUtil::lowerFirst)
                    .collect(Collectors.joining(StrUtil.DASHED));
            headerKeyValues.put(dashLowerHeaderName, currrentRequest.getHeader(headerName));
            headerKeyValues.put(dashUpperHeaderName, currrentRequest.getHeader(headerName));
        }
        return headerKeyValues;
    }

    /**
     * 获取获取当前某个请求头
     *
     * @param headerName
     * @param headerValueType
     * @param <T>
     * @return
     */
    public static <T> T getCurrentRequestHeader(String headerName, boolean ignoreCase, Class<T> headerValueType) {
        headerName = (ignoreCase && StrUtil.isNotBlank(headerName)) ? headerName.toLowerCase() : headerName;
        return getCurrentRequestHeaders().getByPath(headerName, headerValueType);
    }

    /**
     * 获取获取当前某个请求头
     *
     * @param headerName
     * @param headerValueType
     * @param <T>
     * @return
     */
    public static <T> T getCurrentRequestHeader(String headerName, Class<T> headerValueType) {
        return getCurrentRequestHeader(headerName, false, headerValueType);
    }

    /**
     * 获取获取当前某个请求头
     *
     * @param headerName
     * @return
     */
    public static String getCurrentRequestHeader(String headerName, boolean ignoreCase) {
        return getCurrentRequestHeader(headerName, ignoreCase, String.class);
    }

    /**
     * 获取获取当前某个请求头
     *
     * @param headerName
     * @return
     */
    public static String getCurrentRequestHeader(String headerName) {
        return getCurrentRequestHeader(headerName, false);
    }

    /**
     * 获取获取当前某个请求头
     *
     * @param headerName
     * @param <T>
     * @param <M>
     * @return
     */
    public static <T, M> M getCurrentRequestHeader(Func1<T, M> headerName, boolean ignoreCase) {
        String fieldName = LambdaUtil.getFieldName(headerName);
        Class<M> methodResultType = EnhanceLambdaUtil.getMethodResultType(headerName);
        return getCurrentRequestHeader(fieldName, ignoreCase, methodResultType);
    }

    /**
     * 获取获取当前某个请求头
     *
     * @param headerName
     * @param <T>
     * @param <M>
     * @return
     */
    public static <T, M> M getCurrentRequestHeader(Func1<T, M> headerName) {
        return getCurrentRequestHeader(headerName, false);
    }


    /**
     * 获取当前请求属性
     *
     * @return
     */
    public static Dict getCurrentRequestAttributes() {
        HttpServletRequest currrentRequest = getCurrrentRequest();
        Dict attributeKeyValues = Dict.create();
        Enumeration<String> attributeNames = currrentRequest.getAttributeNames();
        while (attributeNames.hasMoreElements()) {
            String attributeName = attributeNames.nextElement();
            attributeKeyValues.put(attributeName, currrentRequest.getAttribute(attributeName));
            attributeKeyValues.put(attributeName.toLowerCase(), currrentRequest.getAttribute(attributeName));
            attributeKeyValues.put(attributeName.toUpperCase(), currrentRequest.getAttribute(attributeName));
        }
        return attributeKeyValues;
    }

    /**
     * 获取当前请求某个属性
     *
     * @param attributeName
     * @param attributeValueType
     * @param <T>
     * @return
     */
    public static <T> T getCurrentRequestAttribute(String attributeName, Class<T> attributeValueType) {
        return getCurrentRequestAttributes().getByPath(attributeName, attributeValueType);
    }

    /**
     * 获取当前请求某个属性
     *
     * @param attributeName
     * @return
     */
    public static String getCurrentRequestAttribute(String attributeName) {
        return getCurrentRequestAttribute(attributeName, String.class);
    }

    /**
     * 获取当前请求某个属性
     *
     * @param attributeName
     * @param <T>
     * @param <M>
     * @return
     */
    public static <T, M> M getCurrentRequestAttribute(Func1<T, M> attributeName) {
        String fieldName = LambdaUtil.getFieldName(attributeName);
        Class<M> methodResultType = EnhanceLambdaUtil.getMethodResultType(attributeName);
        return getCurrentRequestAttribute(fieldName, methodResultType);
    }


    /**
     * 获取当前请求会话session内的属性
     *
     * @return
     */
    public static Dict getCurrentSessionAttributes() {
        HttpServletRequest currrentRequest = getCurrrentRequest();
        Dict attributeKeyValues = Dict.create();
        Enumeration<String> attributeNames = currrentRequest.getSession().getAttributeNames();
        while (attributeNames.hasMoreElements()) {
            String attributeName = attributeNames.nextElement();
            attributeKeyValues.put(attributeName, currrentRequest.getAttribute(attributeName));
            attributeKeyValues.put(attributeName.toLowerCase(), currrentRequest.getAttribute(attributeName));
            attributeKeyValues.put(attributeName.toUpperCase(), currrentRequest.getAttribute(attributeName));
        }
        return attributeKeyValues;
    }

    /**
     * 获取当前请求会话session内某个属性
     *
     * @param attributeName
     * @param attributeValueType
     * @param <T>
     * @return
     */
    public static <T> T getCurrentSessionAttribute(String attributeName, Class<T> attributeValueType) {
        return getCurrentSessionAttributes().getByPath(attributeName, attributeValueType);
    }

    /**
     * 获取当前请求会话session内某个属性
     *
     * @param attributeName
     * @return
     */
    public static String getCurrentSessionAttribute(String attributeName) {
        return getCurrentSessionAttribute(attributeName, String.class);
    }

    /**
     * 获取当前请求会话session内某个属性
     *
     * @param attributeName
     * @param <T>
     * @param <M>
     * @return
     */
    public static <T, M> M getCurrentSessionAttribute(Func1<T, M> attributeName) {
        String fieldName = LambdaUtil.getFieldName(attributeName);
        Class<M> methodResultType = EnhanceLambdaUtil.getMethodResultType(attributeName);
        return getCurrentRequestAttribute(fieldName, methodResultType);
    }


    /**
     * 命令浏览器删除某个cookie
     *
     * @param cookieName
     * @return
     */
    public static Cookie delCookie(String cookieName) {
        Assert.notBlank(cookieName, "cookie名不能缺失,请检查");

        Cookie cookie = new Cookie(cookieName, null);
        cookie.setPath("/");
        cookie.setMaxAge(0);

        Optional.ofNullable(getCurrentResponse())
                .ifPresent(response -> response.addCookie(cookie));
        return cookie;
    }

    /**
     * 添加Cookie
     *
     * @param cookieName       待添加的Cookie
     * @param expireSecondLong cookie过期时间长度(秒)
     * @param <R>
     * @return
     */
    public static <R> Cookie addCookie(Func0<R> cookieName, Integer expireSecondLong) {
        String fieldName = LambdaUtil.getFieldName(cookieName);
        String fieldValue = Convert.toStr(cookieName.callWithRuntimeException());
        return addCookie(fieldName, fieldValue, expireSecondLong);
    }

    public static <R> Cookie addCookie(Func0<R> cookieName) {
        return addCookie(cookieName, null);
    }

    public static <T, R> Cookie addCookie(Func1<T, R> cookieName, String cookieValue) {
        return addCookie(cookieName, cookieValue, null);
    }

    public static <T, R> Cookie addCookie(Func1<T, R> cookieName, String cookieValue, Integer expireSecondLong) {
        return addCookie(LambdaUtil.getFieldName(cookieName), cookieValue, expireSecondLong);
    }


    public static Cookie addCookie(String cookieName, String cookieValue) {
        return addCookie(cookieName, cookieValue, null);
    }

    /**
     * 添加Cookie
     *
     * @param cookieName       cookie名
     * @param cookieValue      cookie值
     * @param expireSecondLong cookie过期时间长度(秒)
     * @return
     */
    public static Cookie addCookie(String cookieName, String cookieValue, Integer expireSecondLong) {
        Cookie cookie = null;
        if (StrUtil.isAllNotBlank(cookieName, cookieValue)) {
            HttpServletResponse currentResponse = getCurrentResponse();
            cookie = new Cookie(cookieName, cookieValue);
            if (expireSecondLong != null) {
                cookie.setMaxAge(expireSecondLong);
            }
            currentResponse.addCookie(cookie);
        }
        return cookie;
    }


    public static List<Cookie> addCookie(Object bean) {
        return addCookie(bean, null);
    }

    /**
     * 对象属性都添加进入本地cookie
     *
     * @param bean
     * @return
     */
    public static List<Cookie> addCookie(Object bean, Integer expireSecondLong) {
        final List cookieList = CollUtil.newArrayList();
        if (ObjectUtil.isNotEmpty(bean)) {
            boolean primitiveFlag = bean.getClass().isPrimitive();
            if (BooleanUtil.isFalse(primitiveFlag)) {
                Map<String, Object> keyValueMap = BeanUtil.beanToMap(bean, false, true);
                keyValueMap.forEach((key, value) -> {
                    if (ClassUtil.isBasicType(value.getClass()) || value.getClass() == String.class) {
                        cookieList.add(addCookie(key, Convert.toStr(value), expireSecondLong));
                    }
                });
            }
        }
        return cookieList;
    }

    /**
     * 获取当前请求的URL前缀
     *
     * @return
     */
    public static String getCurrentContextUrl() {
        HttpServletRequest currrentRequest = getCurrrentRequest();
        String contextPath = StrUtil.format("{}://{}:{}/{}", currrentRequest.getScheme(), currrentRequest.getServerName(), currrentRequest.getServerPort(), currrentRequest.getContextPath());
        contextPath = StrUtil.removeSuffix(contextPath, "/");
        return contextPath;
    }

    /**
     * 获取浏览器用户的IP地址
     *
     * @return
     */
    public static String getClientIp() {
        return ServletUtil.getClientIP(getCurrrentRequest());
    }


    public static List<Integer> getProceedingJoinPointMethodParamHasAnnotationPosition(ProceedingJoinPoint proceedingJoinPoint, Class<? extends Annotation> paramAnnotationClazz) {
        List<Integer> result = CollUtil.newArrayList();
        if (ObjectUtil.isAllNotEmpty(proceedingJoinPoint, paramAnnotationClazz)) {
            Assert.isTrue(proceedingJoinPoint instanceof MethodInvocationProceedingJoinPoint, "非MethodInvocationProceedingJoinPoint类型,请检查");

            MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();

            Annotation[][] parameterAnnotations = signature.getMethod().getParameterAnnotations();

            Parameter[] parameters = signature.getMethod().getParameters();
            for(int parameterIndex = 0; parameterIndex< parameters.length; parameterIndex++) {
                Annotation annotation = parameters[parameterIndex].getAnnotation(paramAnnotationClazz);
                if(annotation != null) {
                    result.add(parameterIndex);
                }
            }

        }
        return result;
    }

    /**
     * 模糊模式
     */
    private enum FuzzyModeEnum {
        LEFT,RIGHT,ALL
    }

    /**
     * 获取Spring环境变量
     * @param key 键名 (右模糊查询)
     * @return
     */
    private static Dict getEnvironmentInfoByRight(String key) {
        return getEnvironmentInfo(key,FuzzyModeEnum.RIGHT);
    }
    private static Dict getEnvironmentInfoByPrefix(String key) {
        return getEnvironmentInfo(key,FuzzyModeEnum.RIGHT);
    }

    /**
     * 获取Spring环境变量
     * @param key 键名 (左模糊查询)
     * @return
     */
    private static Dict getEnvironmentInfoByLeft(String key) {
        return getEnvironmentInfo(key,FuzzyModeEnum.LEFT);
    }

    /**
     * 获取Spring环境变量
     * @param key 键名 (全模糊查询)
     * @return
     */
    private static Dict getEnvironmentInfoByAll(String key) {
        return getEnvironmentInfo(key,FuzzyModeEnum.ALL);
    }

    /**
     * 获取Spring环境变量
     * @param key 键名
     * @param fuzzyModeEnum 模糊模式
     * @return
     */
    private static Dict getEnvironmentInfo(String key, FuzzyModeEnum fuzzyModeEnum) {
        Dict result = Dict.create();
        StandardServletEnvironment environment = (StandardServletEnvironment) getBean(Environment.class);
        MutablePropertySources propertySources = environment.getPropertySources();
        propertySources.stream().forEach(propertySource -> {
            Object source = propertySource.getSource();
            if(source instanceof Map) {
                Map sourceMap = (Map) source;
                Set<Map.Entry> sourceMapEntrys = sourceMap.entrySet();
                sourceMapEntrys.forEach(sourceEntry -> {
                    String keyName = Convert.toStr(sourceEntry.getKey());
                    Object keyValue = sourceEntry.getValue();
                    switch (fuzzyModeEnum) {
                        case ALL: {
                            if(StrUtil.contains(keyName, key)) {
                                result.put(keyName, keyValue);
                            }
                            break;
                        }
                        case LEFT: {
                            if(StrUtil.endWith(keyName, key)) {
                                result.put(keyName, keyValue);
                            }
                            break;
                        }
                        case RIGHT: {
                            if(StrUtil.startWith(keyName, key)) {
                                result.put(keyName, keyValue);
                            }
                            break;
                        }
                    }
                });
            }
        });

        return result;
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值