利用反射机制批量获取request中的参数,并赋值

说明:在servlet中常需要从request中获取参数,同时需要赋值给某个实例对象,当参数较少时可以使用getParameter(String name);从request中获取,但是当数据较多时,代码冗余复杂,没有技术含量,所以利用反射写了一个批量对参数获取并赋值的方法(暂时只支持对String,Integer,int,Float,float,Double,double,java.sql.Date,java.util.Date类型的数据或者数组进行赋值)
import java.lang.reflect.Field;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;


/**
 * 批量从request请求中获取参数值,并赋值给对象
 * 
 * @author dingshuangen
 *
 */
public class Conversion {

	public static  void convert(T t, HttpServletRequest request) {

		// 获取类对象
		Class c = t.getClass();
		try {
			// 获取所有属性
			Field[] fs = c.getDeclaredFields();
			for (Field f : fs) {
				// 设置为可访问
				f.setAccessible(true);
				// 获得属性名
				String name = f.getName();
				// 获得属性的类型名
				Class type = f.getType();
				// 判断是否为数组类型的属性
				if (type.isArray()) {

					System.out.println("s数组转换");
					// 从请求中获取参数数组
					String[] str = request.getParameterValues(name);
					if (str != null) {
						// 判断属性的类型
						if (type == String.class) {

							// 设置属性值
							f.set(t, str);
						} else if (type == int[].class || type == Integer[].class) {// 整型
							// 创建一个整型数组
							Integer[] args = new Integer[str.length];
							// 将String转换为Integer
							for (int i = 0; i < str.length; i++) {
								args[i] = Integer.valueOf(str[i]);
							}

							f.set(t, args);
						} else if (type == Float[].class || type == float[].class) {
							// 创建一个float数组
							Float[] args = new Float[str.length];
							// 将String转换为Float
							for (int i = 0; i < str.length; i++) {
								args[i] = Float.valueOf(str[i]);
							}

							f.set(t, args);
						} else if (type == Double[].class || type == double[].class) {
							// 创建一个Double数组
							Double[] args = new Double[str.length];
							// 将String转换为Double
							for (int i = 0; i < str.length; i++) {
								args[i] = Double.valueOf(str[i]);
							}

							f.set(t, args);
						}else if(type==Date[].class){//转换为java.sql.Date 类型
							Date[] date=new Date[str.length];
							for(int i=0;i




你可能感兴趣的:(javaEE)