欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用于解析HttpServletRequest中参数的公用方法类

程序员文章站 2024-03-07 15:58:03
...
package com.hhh.framework.tools.utils;

import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用于解析HttpServletRequest中参数的公用方法类
 *
 * @author 
 */
public final class RequestResolver {

    /**
     * 从request中获取参数,组装为指定类型的对象
     *
     * @param request  : 前台请求
     * @param objClass : 返回对象的类
     * @param <T>      : 泛型标识
     * @return : 指定类型对象的list
     * @throws IllegalAccessException         : 反射创建对象时抛出异常
     * @throws InstantiationException         : 反射创建对象时抛出异常
     * @throws InvocationTargetException      : 反射赋值时抛出异常
     * @throws NoSuchFieldException           : 获取字段失败的异常
     */
    public static <T> List<T> getListParams(HttpServletRequest request, Class<T> objClass)
            throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchFieldException {
        List<T> objList = null;

        List<Field> fields = getUsedProperties(request, objClass);
        String className = objClass.getSimpleName();
        if (!fields.isEmpty()) {
            int valueLength = getValueLength(request, className, fields);
            objList = new ArrayList<T>(valueLength);
            T obj;
            Object fieldValue = null;
            String fieldName = null;

            if (valueLength == 1) { //仅有一个对应

                obj = objClass.newInstance();

                for (Field fieldInfo : fields) {
                    fieldName = fieldInfo.getName();

                    fieldValue = getFieldValue(fieldInfo, request.getParameter(className + "." + fieldName));
                    if (fieldValue != null) {
                        BeanUtils.setProperty(obj, fieldName, fieldValue);
                    }
                }

                objList.add(obj);

            } else { //多个对应
                for (int i = 0; i < valueLength; i++) {
                    obj = objClass.newInstance();

                    for (Field fieldInfo : fields) {
                        fieldName = fieldInfo.getName();

                        fieldValue = getFieldValue(fieldInfo, request.getParameterValues(className + "." + fieldName)[i]);

                        if (fieldValue != null) {
                            BeanUtils.setProperty(obj, fieldName, fieldValue);
                        }
                    }

                    objList.add(obj);
                }
            }
        }

        return objList;
    }

    /**
     * 进行值转换
     *
     * @param field         : 对应字段
     * @param originalValue : 源数据
     * @return 转换后的值
     */
    private static Object getFieldValue(Field field, String originalValue) {
        if (originalValue != null) {
            originalValue = originalValue.trim();
        }

        if (field.getType().getName().equals("java.util.Date")) {
            return parstDate(originalValue);
        } else {
            return (originalValue == null || originalValue.trim().equals("")) ? null : originalValue;
        }
    }

    /**
     * 检查属性在request中对应的长度是否一致
     *
     * @param request   : 前台请求
     * @param className : 类名
     * @param fields    : 请求中使用到的字段清单
     * @return beanList的长度
     */
    private static int getValueLength(HttpServletRequest request, String className, List<Field> fields)  {

        int preValuesLength = -1;
        int curValuesLength;
        for (Field fieldInfo : fields) {
            curValuesLength = getValuesLength(request, className + "." + fieldInfo.getName());

            if (preValuesLength == -1) {
                preValuesLength = curValuesLength;
            }
        }

        return preValuesLength;
    }

    /**
     * 获取request中指定名称对应的值长度
     *
     * @param request   : 前台请求
     * @param paramName : 参数名称
     * @return 指定参数名称对应的值长度
     */
    private static int getValuesLength(HttpServletRequest request, String paramName) {
        int valuesLength = 0;

        if (request.getParameterValues(paramName) != null) {
            valuesLength = request.getParameterValues(paramName).length;
        } else if (request.getParameter(paramName) != null) {
            valuesLength = 1;
        }

        return valuesLength;
    }

    /**
     * 获取类定义中,在请求中有对应的字段清单
     *
     * @param request  : 前台请求
     * @param objClass : 返回对象的类
     * @param <T>      : 泛型标识
     * @return 使用的字段的List
     * @throws NoSuchFieldException : 获取字段失败的异常
     */
    private static <T> List<Field> getUsedProperties(HttpServletRequest request, Class<T> objClass) throws NoSuchFieldException {
        Enumeration<String> requestParamNames = request.getParameterNames();
        List<Field> fields = new ArrayList<Field>();

        if (requestParamNames != null) {
            String paramName;
            String className = objClass.getSimpleName();
            Field field = null;
            while (requestParamNames.hasMoreElements()) {
                paramName = requestParamNames.nextElement();

                if (paramName.startsWith(className)) {
                    field = objClass.getDeclaredField(paramName.replace(className + ".", ""));
                    fields.add(field);
                }
            }
        }

        return fields;
    }

    /**
     * 字符串转日期对象
     *
     * @param str 字符串日期格式:yyyy-MM-dd HH:mm:ss/yyyy-MM-dd
     * @return
     */
    public static Date parstDate(String str) {
        if (str == null || "".equals(str.trim())) {
            return null;
        }
        SimpleDateFormat formatter = null;

        if (Pattern.matches("^\\d{4}-\\d{2}-\\d{2}$", str)) {
            formatter = new SimpleDateFormat("yyyy-MM-dd");
        } else if (Pattern.matches("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$", str)) {
            formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }

        if (formatter != null) {
            try {
                return formatter.parse(str);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 解析Json数组
     *
     * @param request   : 请求对象
     * @param arrayName : 数据对应的Json属性名
     * @return Json数组中的信息
     */
    public static List<Map<String, String>> resolveJsonArray(HttpServletRequest request, String arrayName) {
        List<Map<String, String>> results = new ArrayList<Map<String, String>>();
        List<String[]> paramInfos = getParamNames(request, arrayName);

        //手动排序,确保一个对象的属性连续放置
        Collections.sort(paramInfos, new Comparator<String[]>() {
            @Override
            public int compare(String[] o1, String[] o2) {
                return o1[0].compareTo(o2[0]);
            }
        });

        String findIndexStartPatternRule = arrayName + "\\[";
        String findIndexEndPatternRule = arrayName + "\\[\\d+\\]";
        Pattern findIndexStartPattern = Pattern.compile(findIndexStartPatternRule);
        Matcher findIndexStartMatcher = null;
        Pattern findIndexEndPattern = Pattern.compile(findIndexEndPatternRule);
        Matcher findIndexEndMatcher = null;
        String curObjIndex = null;
        String preObjIndex = null;
        Map<String, String> result = null;
        int indexStart = 0;
        int indexEnd = 0;
        for (String[] paramInfo : paramInfos) {
            findIndexStartMatcher = findIndexStartPattern.matcher(paramInfo[0]);
            findIndexStartMatcher.find();
            indexStart = findIndexStartMatcher.end();

            findIndexEndMatcher = findIndexEndPattern.matcher(paramInfo[0]);
            findIndexEndMatcher.find();
            indexEnd = findIndexEndMatcher.end() - 1;

            curObjIndex = paramInfo[0].substring(indexStart, indexEnd);

            if (!curObjIndex.equals(preObjIndex)) {
                result = new HashMap<String, String>();
                results.add(result);

                preObjIndex = curObjIndex;
            }

            result.put(paramInfo[1], request.getParameter(paramInfo[0]));
        }

        return results;
    }

    /**
     * 抽取request中的参数名
     *
     * @param request   : 请求对象
     * @param arrayName : 数据对应的Json属性名
     * @return 符合条件的参数名
     */
    private static List<String[]> getParamNames(HttpServletRequest request, String arrayName) {
        Enumeration<String> requestParamNames = request.getParameterNames();
        List<String[]> paramNames = new ArrayList<String[]>();
        String checkPatternRule = "^" + arrayName + "\\[\\d+\\]\\[[a-zA-Z0-9_.]+\\]$";
        String findPatternRule = arrayName + "\\[\\d+\\]";
        Pattern findPattern = Pattern.compile(findPatternRule);

        if (requestParamNames != null) {
            String paramName;
            while (requestParamNames.hasMoreElements()) {
                paramName = requestParamNames.nextElement();

                if (Pattern.matches(checkPatternRule, paramName)) {
                    paramNames.add(new String[]{
                            paramName, getFieldName(paramName, findPattern)
                    });
                }
            }
        }

        return paramNames;
    }

    /**
     * 从Json数组参数中抽离真正的参数名
     *
     * @param paramName   : 参数名
     * @param findPattern : 匹配方式
     * @return 真正的参数名称
     */
    private static String getFieldName(String paramName, Pattern findPattern) {
        Matcher matcher = findPattern.matcher(paramName);
        matcher.find();
        int start = matcher.end();
        return paramName.substring(start + 1, paramName.length() - 1);
    }

    /**
     * 工具类无需创建实例
     */
    private RequestResolver() {
    }
}

 

相关标签: 工具类 java