一个简单的注册 反射(写在servlet中)

 

 1     public void doPost(HttpServletRequest request, HttpServletResponse response)
 2     throws ServletException, IOException {
 3 
 4         try{
 5             request.setCharacterEncoding("Utf-8");
 6             response.setCharacterEncoding("utf-8");
 7             response.setContentType("text/html");
 8             PrintWriter out = response.getWriter();
 9             
10             String nstr = request.getParameter("name");
11             String pstr = request.getParameter("pwd");
12             
13             /*********开始反射机制***********************************************************************************/
14             //1. 根据包创建类
15             Class<?> c = Class.forName("entity.User");            
16             //2. 根据类创建对象
17             User obj = (User) c.newInstance();
18             //3. 找到该对象的所有方法
19             Method[] methods = obj.getClass().getDeclaredMethods();
20             
21             //4. 创建StringBuffer对象将 对象属性封装成 Jeson格式
22             StringBuffer sb = new StringBuffer();            
23             sb.append("{");
24             for( Method method : methods) {
25                 if( method.getName().startsWith("get")) {
26                     Object o = method.invoke(obj);
27                     sb.append(" \" "+method.getName().replaceAll("get", "")+" \" ");
28                     sb.append(":");
29                     sb.append(" \" "+o+" \" ");
30                     sb.append(",");
31                 }
32 
33             }
34             sb.deleteCharAt(sb.length()-1);
35             sb.append("}");
36             
37             //5. 判断方法,进行操作为属性赋值
38             for( Method method : methods ) {
39                 if( method.getName().equals("setName")) {
40                     method.invoke(obj, nstr);
41                 }
42                 if( method.getName().equals("setPwd")) {
43                     method.invoke(obj, pstr);
44                 }
45             }
46             /*******************以上反射部分到此结束***********下边是正常的业务交互**************************************/
47             //6. 与service层进行业务
48             IUserService service = new UserServiceImpl();
49             int result = service.returnRegisterResult(obj);
50             if( result ==1 ){
51                  request.getRequestDispatcher("page/LoginSuccess.jsp").forward(request, response);
52             } else {
53                 out.println("<script>");
54                 out.println("alert('用户名或密码错误!');");
55                 out.println("location='" + request.getContextPath() + "/page/Register.jsp'");
56                 out.println("</script>");
57             }
58     }catch(Exception e){
59         e.printStackTrace();
60     }
61 }

 

posted @ 2015-01-11 16:58  江湖一笑  阅读(288)  评论(0编辑  收藏  举报