1

为什么想这么做?

​ 在用传统Servlet做WEB项目的时候,涉及到构造一个field极多的Bean的业务,并且各个field类型不同,尽管在SpringMVC拥有属性绑定的特性,可如果不使用框架,该如何简化这个操作呢?

怎么做?

​ 首先想到的是用一个Map将各个属性put进去,然后遍历这个Map利用反射构造属性。

代码展示

​ 出于演示我只构造了只有3个field的Bean,不过重点不在数量。

​ Person.java

public class Person {
   private String name;
   private Integer price;
   private String love;

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", price=" + price +
                ", love='" + love + '\'' +
                '}';
    }

    public void setName(String name) {
        System.out.println("----------------------------");
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

    public String getLove() {
        return love;
    }

    public void setLove(String love) {
        this.love = love;
    }
}

以及在Servlet中最重点的用反射操作Bean

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Bean extends HttpServlet {


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Map maps= req.getParameterMap();
            Map<String,String> map=new HashMap<String, String>();
            Iterator iterator=maps.entrySet().iterator();
            while (iterator.hasNext()){
                Map.Entry entry= (Map.Entry) iterator.next();
                String key= (String) entry.getKey();
                map.put(key,req.getParameter(key));
            }
            Person person= (Person) build(Person.class,map);
            System.out.println(person);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public static Object build(Class clz,Map fieldMap)
            throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Field[] fields=clz.getDeclaredFields();
        Object obj=clz.newInstance();
        Object value=null;
        for (int i=0;i<fields.length;i++){
            String[] type= (""+fields[i]).split(" ");
            String[] setMtd=type[2].split("\\.");
            if ("java.lang.Integer".equals(type[1].toString())){
                value=Integer.parseInt(String.valueOf(fieldMap.get(setMtd[1])));
            }
            if ("java.lang.String".equals(type[1].toString())){
                value= fieldMap.get(setMtd[1]);
            }
            fields[i].setAccessible(true);
            fields[i].set(obj,value);
        }
        return obj;
    }
}

一些总结

  1. String.split()方法在对“ . ” 操作的时候应该用“\\.”
  2. 利用request的getParameterMap()方法获取到的是Map<String,String[]> map ,所以还要遍历一次map构造一个Map <String,String> map
  3. 类的动态加载生成的确强大,以后会注意发掘更多的用途

心源意码
75 声望13 粉丝