首页 > 代码库 > 通过反射自动封装表单字段

通过反射自动封装表单字段

package cn.jbit.util;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.spi.ServiceRegistry.Filter;
import javax.servlet.http.HttpServletRequest;

public class RequestUtil {
	public static Object getObject(HttpServletRequest request, Class clazz,
			String enc) throws UnsupportedEncodingException,
			IntrospectionException, InstantiationException, IllegalAccessException {

		Field[] fields = clazz.getDeclaredFields();
		Object obj = clazz.newInstance();
		request.setCharacterEncoding(enc);
		Map<String, String> map = new HashMap<String, String>();
		if (request.getMethod().equals("GET")) {
			System.out.println("-----------GET--------------------");
			String query = URLDecoder.decode(request.getQueryString(), enc);
			String[] str = query.split("&");
			for (String string : str) {
				try {
					map.put(string.split("=")[0], string.split("=")[1]);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} else {
			System.out.println("-----------POST--------------------");
			Map<String, String[]> parmmap = request.getParameterMap();
			for (String key : parmmap.keySet()) {
				try {
					map.put(key, parmmap.get(key)[0]);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		for (Field field : fields) {
			try {
				PropertyDescriptor pd = new PropertyDescriptor(field.getName(),
						clazz);
				Method seter = pd.getWriteMethod();
				if (field.getType().getName().equals(int.class.getName())
						|| field.getType().getName()
								.equals(Integer.class.getName())) {
					seter.invoke(obj, Integer.valueOf(map.get(field.getName())));
				} else if (field.getType().getName()
						.equals(Date.class.getName())) {
					SimpleDateFormat sdf = new SimpleDateFormat();
					Date date = sdf.parse(map.get(field.getName()));
					seter.invoke(obj, date);
				} else if (field.getType().getName()
						.equals(Double.class.getName())
						|| field.getType().getName()
								.equals(double.class.getName())) {
					seter.invoke(obj, Double.valueOf(map.get(field.getName())));
				} else if (field.getType().getName()
						.equals(String.class.getName())) {
					seter.invoke(obj, map.get(field.getName()));
				}

			} catch (Exception e) {
				System.out.println("异常 了");
			}

		}
		return obj;
	}
}

通过反射自动封装表单字段