利用java类的反射机制,实现了 映射 获得post(get)的参数 的BaseServlet

这几天一直在研究java的反射机制,正好作业需要写servlet,为了增加一点难度,就用java的反射机制来映射获取前端post或get过来的参数

 

1.该方式有点像struts2 利用映射获取前端的参数,目前只能映射javabean的Integer,String两种类型。有兴趣的同学可以自行添加别的类的判断

直接上代码,映射方式被我封装成了一个BaseServlet

 

2.直接用get方式访问http://localhost:8080/webTest/query?student.sname=1&student.sage=12      

   参数可以缺省,也可以利用post方式,这边为方便调用,就只用了get

 

3.得到的结果

  1 package mangues.base;
  2 
  3 import java.io.IOException;
  4 import java.lang.reflect.Method;
  5 import java.util.ArrayList;
  6 import java.util.List;
  7 import java.util.Map;
  8 import javax.servlet.ServletException;
  9 import javax.servlet.annotation.WebServlet;
 10 import javax.servlet.http.HttpServlet;
 11 import javax.servlet.http.HttpServletRequest;
 12 import javax.servlet.http.HttpServletResponse;
 13 import mangues.model.Student;
 14 
 15 /**
 16  * 
 17  * @ClassName: BaseServlet
 18  * @Description: 自定义servlet基类,实现参数的映射
 19  * @author mangues
 20  * @date 2015-7-21
 21  */
 22 public abstract class BaseServlet extends HttpServlet {
 23     private List<String> var = null; // 存储字段名
 24     private List<String> vars = null; // 存储字段名
 25     private List<Method> ms = null; // 方法
 26 
 27     @Override
 28     public void init() throws ServletException {
 29         super.init();
 30         getVar();
 31     }
 32 
 33     // 是否自定义变量
 34     private boolean isParameter(String mName) {
 35         String con[] = { "getServletContext", "getServletConfig",
 36                 "getServletName", "getInitParameter", "getInitParameterNames",
 37                 "getServletInfo" };
 38         if (mName.startsWith("set") && !mName.startsWith("getClass")) {
 39             for (String nameString : con) {
 40                 if (mName.equals(nameString)) {
 41                     return false;
 42                 }
 43             }
 44             return true;
 45         } else {
 46             return false;
 47         }
 48 
 49     }
 50    //初始化
 51     private void getVar() {
 52         var = new ArrayList<String>();
 53         vars = new ArrayList<String>();
 54         ms = new ArrayList<Method>();
 55         Class classType = this.getClass();
 56         Method method[] = classType.getMethods();
 57         for (Method m : method) { // 遍历方法
 58             String mName = m.getName(); // 方法名
 59             if (isParameter(mName)) {
 60                 try {
 61                     // 获取字段名
 62                     String fieldName = mName.substring(3, mName.length())
 63                             .toLowerCase();
 64                     vars.add(fieldName);
 65                     String ds = m.toString();
 66                     int i = ds.indexOf("(");
 67                     int j = ds.indexOf(")");
 68                     String str = ds.substring(i + 1, j);
 69                     var.add(str);
 70                     ms.add(m);
 71                 } catch (Exception e) {
 72                     e.printStackTrace();
 73                 }
 74 
 75             }
 76         }
 77     }
 78 
 79     public void doGet(HttpServletRequest request, HttpServletResponse response)
 80             throws ServletException, IOException {
 81         doPost(request, response);
 82     }
 83 
 84     public void doPost(HttpServletRequest request, HttpServletResponse response)
 85             throws ServletException, IOException {
 86         request.setCharacterEncoding("utf-8");
 87         response.setCharacterEncoding("utf-8");
 88         Map<String, String[]> map = request.getParameterMap(); // 这个方法是获取用户请求时携带的参数名称和参数值,并将其组装成一个Map对象
 89         for (int i = 0; i < vars.size(); i++) {
 90             String strs = vars.get(i); // 遍历出变量名
 91             String str = var.get(i); // 遍历出bean位置
 92             Method mehMethod = ms.get(i); // 方法
 93             String parameterKey;
 94             Class classType;
 95             try {
 96                 classType = Class.forName(str);
 97                 Object o = classType.newInstance();
 98                 Method[] methods = classType.getMethods(); // 获取方法
 99                 for (Method m : methods) { // 遍历方法
100                     String mName = m.getName(); // 方法名
101                     if (mName.startsWith("set")) {
102                         // 获取字段名
103                         String fieldName = mName.substring(3, mName.length())
104                                 .toLowerCase();
105                         parameterKey = strs + "." + fieldName;
106                         // 赋值
107                         if (map.get(parameterKey) != null) {
108                             String key[] = map.get(parameterKey);
109                             String ds = m.toString();
110                             int i1 = ds.indexOf("(");
111                             int j1 = ds.indexOf(")");
112                             String str1 = ds.substring(i1 + 1, j1);
113                             if (str1.equals("java.lang.Integer")
114                                     || str1.equals("int")) {
115                                 // 如果是int类型
116                                 int ip = Integer.parseInt(key[0]);
117                                 m.invoke(o, ip);
118                             } else {
119                                 m.invoke(o, key[0]);
120                             }
121 
122                         }
123                     }
124                 }
125                 if (o != null) {
126 
127                     mehMethod.invoke(this, o);
128                 }
129 
130             } catch (Exception e) {
131                 // TODO Auto-generated catch block
132                 e.printStackTrace();
133             }
134         }
135 
136         manguesPost(request, response);
137     }
138 
139     protected abstract void manguesPost(HttpServletRequest request,
140             HttpServletResponse response);
141 }

 

 

下面是 一个简单的继承servlet,只需要利用get方式访问

package mangues.servlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mangues.base.BaseServlet;
import mangues.model.Student;

@WebServlet(urlPatterns = { "/query" })
public class AddServlet extends BaseServlet {
    private Student student;
    public Student getStudent() {
        return student;
    }
    public void setStudent(Student student) {
        this.student = student;
    }

    @Override
    protected void manguesPost(HttpServletRequest request,
            HttpServletResponse response) {
          System.out.println(student.getSname());
    }

}

 

 

下面是需要映射的Bean

package mangues.model;

public class Student {
    private String sno; //学号
    private String sname;//姓名
    private Integer sage; //年龄
    private String ssex; //性别
    public Student() {
        super();
    }
    public Student(String sno, String sname, Integer sage, String ssex) {
        super();
        this.sno = sno;
        this.sname = sname;
        this.sage = sage;
        this.ssex = ssex;
    }
    public String getSno() {
        return sno;
    }
    public void setSno(String sno) {
        this.sno = sno;
    }
    public String getSname() {
        return sname;
    }
    public void setSname(String sname) {
        this.sname = sname;
    }
    public Integer getSage() {
        return sage;
    }
    public void setSage(Integer sage) {
        this.sage = sage;
    }
    public String getSsex() {
        return ssex;
    }
    public void setSsex(String ssex) {
        this.ssex = ssex;
    }
    
    
}

 

posted @ 2015-07-21 16:46  mangues  阅读(2745)  评论(0编辑  收藏  举报