|
| 1 | +package spms.bind; |
| 2 | + |
| 3 | +import java.lang.reflect.Method; |
| 4 | +import java.util.Date; |
| 5 | +import java.util.Set; |
| 6 | + |
| 7 | +import javax.servlet.ServletRequest; |
| 8 | + |
| 9 | +public class ServletRequestDataBinder { |
| 10 | + public static Object bind( |
| 11 | + ServletRequest request, Class<?> dataType, String dataName) |
| 12 | + throws Exception { |
| 13 | + if (isPrimitiveType(dataType)) { |
| 14 | + return createValueObject(dataType, request.getParameter(dataName)); |
| 15 | + } |
| 16 | + |
| 17 | + Set<String> paramNames = request.getParameterMap().keySet(); |
| 18 | + Object dataObject = dataType.newInstance(); |
| 19 | + Method m = null; |
| 20 | + |
| 21 | + for (String paramName : paramNames) { |
| 22 | + m = findSetter(dataType, paramName); |
| 23 | + if (m != null) { |
| 24 | + m.invoke(dataObject, createValueObject(m.getParameterTypes()[0], |
| 25 | + request.getParameter(paramName))); |
| 26 | + } |
| 27 | + } |
| 28 | + return dataObject; |
| 29 | + } |
| 30 | + |
| 31 | + private static boolean isPrimitiveType(Class<?> type) { |
| 32 | + if (type.getName().equals("int") || type == Integer.class || |
| 33 | + type.getName().equals("long") || type == Long.class || |
| 34 | + type.getName().equals("float") || type == Float.class || |
| 35 | + type.getName().equals("double") || type == Double.class || |
| 36 | + type.getName().equals("boolean") || type == Boolean.class || |
| 37 | + type == Date.class || type == String.class) { |
| 38 | + return true; |
| 39 | + } |
| 40 | + return false; |
| 41 | + } |
| 42 | + |
| 43 | + private static Object createValueObject(Class<?> type, String value) { |
| 44 | + if (type.getName().equals("int") || type == Integer.class) { |
| 45 | + return new Integer(value); |
| 46 | + } else if (type.getName().equals("float") || type == Float.class) { |
| 47 | + return new Float(value); |
| 48 | + } else if (type.getName().equals("double") || type == Double.class) { |
| 49 | + return new Double(value); |
| 50 | + } else if (type.getName().equals("long") || type == Long.class) { |
| 51 | + return new Long(value); |
| 52 | + } else if (type.getName().equals("boolean") || type == Boolean.class) { |
| 53 | + return new Boolean(value); |
| 54 | + } else if (type == Date.class) { |
| 55 | + return java.sql.Date.valueOf(value); |
| 56 | + } else { |
| 57 | + return value; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + private static Method findSetter(Class<?> type, String name) { |
| 62 | + Method[] methods = type.getMethods(); |
| 63 | + |
| 64 | + String propName = null; |
| 65 | + for (Method m : methods) { |
| 66 | + if (!m.getName().startsWith("set")) continue; |
| 67 | + |
| 68 | + propName = m.getName().substring(3); |
| 69 | + if (propName.toLowerCase().equals(name.toLowerCase())) { |
| 70 | + return m; |
| 71 | + } |
| 72 | + } |
| 73 | + return null; |
| 74 | + } |
| 75 | +} |
0 commit comments