java - 将 servlet 请求参数映射到 java 类的最佳方法是什么?

标签 java reflection servlets mapping

Possible Duplicate:
Easy way of populating Javabeans based on request parameters

嗨,

我有一个带有一组搜索参数的 Java 对象,等等。就像

public class SearchRequest {

private String customerName;
private String city;
...
}

此请求必须由服务器请求填充。

但是不要编写这样的代码

...

SearchRequest searchRequest = new SearchRequest();

if (request.getParameter("customerName") != null)
{ 
    searchRequest.setCustomerName(request.getParameter("customerName"));
}
if (request.getParameter("city") != null)
{ 
    searchRequest.setCity(request.getParameter("city"));
}

... 我正在寻找一种更通用的方法。

我正在检查映射工具Dozer,但没有找到处理此映射的好方法。

现在我认为反射(reflection)是一种选择。 这是真的? 如果是这样,有人有代码片段,如何通过反射来完成此操作?

最佳答案

我认罪:

public void save(HttpServletRequest req, Object obj) {
    Set<String> names = new HashSet<String>();
    @SuppressWarnings("unchecked")
    Enumeration<String> enm = req.getParameterNames();
    while (enm.hasMoreElements()) {
        names.add(enm.nextElement());
    }
    Class clazz = obj.getClass();
    while (clazz != Object.class && !names.isEmpty()) {
        for (Field f: clazz.getDeclaredFields()) {
            if (!Modifier.isTransient(f.getModifiers())) {
                String name = f.getName();
                if (names.contains(name)) {
                    try {
                        names.remove(name);
                        f.setAccessible(true);
                        Object val = convertValue(req, f.getType(),
                                name);
                        f.set(obj, val);
                    } catch (ParseException ex) {
                        LOG.error("Error assigning field", ex);
                    } catch (IllegalAccessException ex) {
                        LOG.error("Error assigning field", ex);
                    }
                }
            }
        }
        clazz = clazz.getSuperclass();
    }
}

private Object convertValue(HttpServletRequest req, Class<?> type,
        String name) throws ParseException {
    if (type.isArray()) {
        Class<?> elemType = type.getComponentType();
        String strings[] = req.getParameterValues(name);
        if (strings == null || strings.length == 0) {
            return new Object[0];
        }
        Object array = Array.newInstance(elemType, strings.length);
        for (int i = 0; i < strings.length; ++i) {
            Object val = parse(elemType, strings[i]);
            Array.set(array, i, val);
        }
        return array;
    } else {
        String s = req.getParameter(name);
        if (s == null) {
            return null;
        }
        return parse(type, s);
    }
}

public static Object parse(Class<?> type, String value)
        throws ParseException {
    if (type == String.class) {
        return value;
    } else if (value == null || value.length() == 0) {
        return null;
    } else if (Enum.class.isAssignableFrom(type)) {
        @SuppressWarnings("unchecked")
        Object result = Enum.valueOf((Class<? extends Enum>)type, value);
        return result;
    } else if (type == boolean.class || type == Boolean.class) {
        return "true".equals(value);
    } else if (type == byte.class || type == Byte.class) {
        return Byte.valueOf(value);
    } else if (type == short.class || type == Short.class) {
        return Short.valueOf(value);
    } else if (type == int.class || type == Integer.class) {
        return Integer.valueOf(value);
    } else if (type == long.class || type == Long.class) {
        return Long.valueOf(value);
    } else if (type == float.class || type == Float.class) {
        return Float.valueOf(value);
    } else if (type == double.class || type == Double.class) {
        return Double.valueOf(value);
    } else if (type == Date.class) {
            return new SimpleDateFormat("dd/MM/yyyy").parse(value);
    } else if (type == BigDecimal.class) {
        DecimalFormat format = getDecimalFormat("0.00");
        return format.parse(value);
    } else {
        throw new RuntimeException("Cannot convert value of type " + type);
    }
}

private static DecimalFormat getDecimalFormat(String pattern) {
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator('.');
    DecimalFormat format = new DecimalFormat(pattern);
    format.setParseBigDecimal(true);
    format.setDecimalFormatSymbols(symbols);
    return format;
}

关于java - 将 servlet 请求参数映射到 java 类的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5718557/

相关文章:

java - 这是在java中添加图书列表的最佳方式

java - Web应用的Ping实现方法

c# - 具有泛型重载的 GetMethod

C# 在未知对象中设置属性

从 Web 服务器下载文件时出现 java.lang.IllegalStateException servlet 异常

java - 该网址在本地主机中有效,但在服务器中无效

java - 无法从 Servlet 检索数据

java - JSP 到 PDF 转换器 由 jsPDF

java - 属性未找到异常 : Property 'X' not found on type X

c# - 在 C# 中使用反射初始化 IEnumerable 属性 (propertyInfo)