Spring boot中HttpServletRequest.getParameterMap 转换成对象

我们知道HttpServletRequest.getParameterMap 得到的所有的数据都是只读的,我们可以把所有的数据放到一个新的内存对象中。

Map, String[]> requestParams = request.getParameterMap();
Map, Object> paramsMap = new HashMap<>(requestParams.size());
for (Map.Entry, String[]> entry : requestParams.entrySet()) {
    Object valueStr = (entry.getValue() == null) ? null : entry.getValue()[0];
    paramsMap.put(entry.getKey(), valueStr);
}

这个采用了和spring 相同的处理方式。

然后把map转换为pojo!转换的时候,会出现没有注册我们的string 转换为date的类型,我们先在转换之前,注册一下


ConvertUtils.register(new Converter() {
    @Override
    public <T> T convert(Class<T> aClass, Object o) {
        if (null == o) return null;
        if (!(o instanceof String)) {
            throw new ConversionException("只支持字符串转换");
        } else if ("".equals(((String) o).trim())) {
            return null;
        }
        SimpleDateFormat format;
        if (((String) o).length() > 10) {
            format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } else {
            format = new SimpleDateFormat("yyyy-MM-dd");
        }
        try {
            return (T) format.parse((String) o);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}, Date.class);

我的处理字符串的过程中,我们对字符串的长度做了不同的处理。

这个来自银联商务数据的不同格式的时间字符串。

最后采用BeanUtils.populate来处理。

try {
    bean = tClass.newInstance();
    BeanUtils.populate(bean, map);
} catch (IllegalAccessException | InvocationTargetException | InstantiationException e) {
    e.printStackTrace();
}

处理的整个方法

public static <T> T mapToBean(Map, Object> map, Classextends T> tClass) {
    T bean = null;
    /**
     * 因为不支持我们在前面封装的那个转换类
     * 所以在这个这个位置自己注册一个新的
     * 转换类,用来把string to date
     */
    ConvertUtils.register(new Converter() {
        @Override
        public <T> T convert(Class<T> aClass, Object o) {
            if (null == o) return null;
            if (!(o instanceof String)) {
                throw new ConversionException("只支持字符串转换");
            } else if ("".equals(((String) o).trim())) {
                return null;
            }
            SimpleDateFormat format;
            if (((String) o).length() > 10) {
                format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            } else {
                format = new SimpleDateFormat("yyyy-MM-dd");
            }
            try {
                return (T) format.parse((String) o);
            } catch (ParseException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }, Date.class);
    try {
        bean = tClass.newInstance();
        BeanUtils.populate(bean, map);
    } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) {
        e.printStackTrace();
    }
    return bean;
}
完!!!


你可能感兴趣的:(java)