Java工具集-网络参数工具(将请求参数封装成Map)

2019-10-26 21:08:18 浏览数 (1)

添加依赖
代码语言:javascript复制
		<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>
代码示例
代码语言:javascript复制
package *;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @program: simple_tools
 * @description: 将请求参数转成Map集合
 * @author: ChenWenLong
 * @create: 2019-10-18 13:46
 **/
public class MapDataUtil {

    /**
     * 功能描述:
     * 〈将请求参数转换成Map集合〉
     *
     * @params : [request]
     * @return : java.util.Map<java.lang.String,java.lang.Object>
     * @author : cwl
     * @date : 2019/10/18 13:47
     */
    public static Map<String, Object> convertDataMap(HttpServletRequest request) {
        Map<String, String[]> properties = request.getParameterMap();
        Map<String, Object> returnMap = new HashMap<String, Object>();
        Iterator<?> entries = properties.entrySet().iterator();
        Map.Entry<?, ?> entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry<?, ?>) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj) {
                value = "";
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (int i = 0; i < values.length; i  ) {
                    value = values[i]   ",";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        return returnMap;
    }
}

0 人点赞