基于REST的MVC架构设计与实现

    在上一篇随笔已经讲述了REST的WEB serivce架构的相关知识,并且搭建了一个非常简单的实例,在另一篇随笔中也写了ajax用JSON序列化数据的传输,在这篇文章将结合前两篇随笔所讲的知识做一个稍显复杂但适用的小实例。

    REST强调客户端与服务器端之间服务调用的模式,而MVC强调的应用程序的结构层次。

    关于REST的知识我在这里就不多说了,参考前面的文章。

 

 一.什么是MVC

    MVC是一个框架模式,它强制性的使应用程序的输入处理输出分开。使用MVC应用程序被分成三个核心部件:模型、视图、控制器。它们各自处理自己的任务。

   

 视图

  视图是用户看到并与之交互的界面。对老式的Web应用程序来说,视图就是由HTML元素组成的界面,在新式的Web应用程序中,HTML依旧在视图中扮演着重要的角色,但一些新的技术已层出不穷,它们包括Adobe Flash和象XHTML,XML/XSL,WML等一些标识语言和Web services. 

  MVC好处是它能为应用程序处理很多不同的视图。在视图中其实没有真正的处理发生,不管这些数据是联机存储的还是一个雇员列表,作为视图来讲,它只是作为一种输出数据并允许用户操纵的方式。

模型

  模型表示企业数据和业务规则。在MVC的三个部件中,模型拥有最多的处理任务。例如它可能用象EJBs和ColdFusion Components这样的构件对象来处理数据库,被模型返回的数据是中立的,就是说模型与数据格式无关,这样一个模型能为多个视图提供数据,由于应用于模型的代码只需写一次就可以被多个视图重用,所以减少了代码的重复性。[6]

控制器

控制器接受用户的输入并调用模型和视图去完成用户的需求,所以当单击Web页面中的超链接和发送HTML表单时,控制器本身不输出任何东西和做任何处理。它只是接收请求并决定调用哪个模型构件去处理请求,然后再确定用哪个视图来显示返回的数据。

二.实例分析

    我做的这个实例主要是完成学生信息的管理。数据比较简单,但麻雀虽小,五脏俱全,足以说明问题。

    1.数据库设计

     DB用的是mysql,只设计了是一张用户表,如下:

列名类型大小描述
useridbigint20primary key(自动编号)
usernametext not null
sextext not null
phonetext not null
addresstext not null
constellation(星座)text not null

 

 

 

 

 

 

 

 

 

2.应用程序架构

   采用MVC架构

  View层放在REST客户端,而Control层和Model层放在REST服务器端: 

  View层设计:

            

View Code
 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>REST+MVC架构示例</title>
 8 <style>
 9    table{border-collapse:collapse;}
10 table,th, td
11 {
12   border: 1px solid gray;
13   padding:3px;
14   font-size:12px;
15 }
16 .tablehead { background-color:#98eee7; font-weight:bold;}
17 .button{ width:50px;heigth:20px;}
18 </style>
19 <script type="text/javascript" src="script/ajaxRequest.js"></script>
20 <script type="text/javascript" src="script/json2.js"></script>
21 </head>
22 <body>
23 <strong>REST+MVC示例</strong>
24 数据传输:采用JSON序列化
25 <hr>
26 <input type="button" value="学生列表" onclick="getAjaxJson()">
27 <input type="button" value="添加新同学" onclick="addAjaxJson()">
28 <div id="showsuccess" style="font-size:12px;color:red;height:15px"></div>
29 <hr>
30 <div id="showout"></div>
31 <div id="addpanel" style="position:absolute;display:none; width:250px;top: 150px; left: 200px;background-color:#ccc;border: solid 2px #329df0;">
32 <div id="title" style="background-color: #329df0; cursor: move; height: 20px; color: #fff;font-size: 13px; padding-top: 5px; padding-left: 10px;"></div>
33 <table style="width:100%">
34 <tr>
35 <td>姓名:</td><td><input id="name" type="text"></td></tr>
36 <tr><td>性别:</td><td>
37 <select id="sex"><option value="男"></option><option value="女"></option></select></td></tr>
38 <tr><td>电话:</td><td><input id="tel" type="text"></td></tr>
39 <tr><td>地址:</td><td><input id="address" type="text"></td></tr>
40 <tr><td>星座:</td>
41 <td><select id="star">
42 <option value="白羊座">白羊座</option>
43 <option value="金牛座">金牛座</option>
44 <option value="双子座">双子座</option>
45 <option value="巨蟹座">巨蟹座</option>
46 <option value="狮子座">狮子座</option>
47 <option value="处女座">处女座</option>
48 <option value="天秤座">天秤座</option>
49 <option value="天蝎座">天蝎座</option>
50 <option value="人马座">人马座</option>
51 <option value="摩羯座">摩羯座</option>
52 <option value="宝瓶座">宝瓶座</option>
53 <option value="双鱼座">双鱼座</option>
54 </select><tr>
55 <tr><td colspan="2" align="center"><input  type="button" class="button" value="提交" id="addedit" onclick="addrecord()">&nbsp;&nbsp;<input type="button" class="button" value="关闭" onclick="closepanel()"></td><tr>
56 </table>
57   </div>
58 <script type="text/javascript">
59 var posX;
60 var posY; 
61 fdiv = document.getElementById("addpanel"); 
62 document.getElementById("title").onmousedown=function(e)
63 {
64   if(!e) e = window.event; //如果是IE
65   
66   //记录鼠标与拖动层上下边边距间的相对位移
67   posX = e.clientX - parseInt(fdiv.style.left);
68   posY = e.clientY - parseInt(fdiv.style.top);
69   document.onmousemove = mousemove; 
70 }
71 document.onmouseup = function()
72 {
73   document.onmousemove = null;
74 }
75 function mousemove(ev)
76 {
77   if(ev==null) ev = window.event;//如果是IE
78   fdiv.style.left = (ev.clientX - posX) + "px";
79   fdiv.style.top = (ev.clientY - posY) + "px";
80 }
81 </script>
82 </body>
83 </html>

    web.xml配置文件:

   

View Code
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 3   <display-name>jsonexample</display-name>
 4  <servlet>
 5         <servlet-name>myServlet</servlet-name>
 6         <servlet-class>com.myServlet</servlet-class>
 7 </servlet>
 8 <servlet-mapping>
 9     <servlet-name>myServlet</servlet-name>
10     <url-pattern>/myServlet</url-pattern>
11 </servlet-mapping>
12 </web-app>

 

    通信、显示脚本:

   

View Code
  1 /*
  2  * name:getTransport
  3  * create XMLHttpRequest
  4  */
  5  var xmlhttp=null;
  6  var flag=null;
  7  var data=null;
  8  var id=null;
  9  function getHttpRequest() 
 10  {
 11    try
 12    {
 13     xmlhttp=new ActiveXObject('Msxml2.XMLHTTP');
 14    }
 15    catch(e)
 16    {
 17         try
 18           {
 19                 xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
 20           }
 21           catch(e1)
 22           {
 23               xmlhttp=new XMLHttpRequest();
 24           }
 25        
 26    }
 27  }
 28  
 29 
 30  
 31 function httpGet(url,method,data)
 32 {
 33  if(xmlhttp==null)
 34  getHttpRequest();
 35  xmlhttp.open(method,url +"?"+data,true);//有回调函数时为true,没有时false
 36  xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 37  xmlhttp.setRequestHeader("Content-Length",data.length);
 38  xmlhttp.onreadystatechange=getCallback;
 39  xmlhttp.send (null);
 40 }
 41 
 42 function getCallback()
 43 {
 44      if(xmlhttp.readyState==4)
 45      {  
 46        if(xmlhttp.status==200)
 47        {            
 48            var xmlDoc=xmlhttp.responseText;
 49            data=eval(xmlDoc);
 50            var tableFormat="<table rules='all' ><tr><td class='tablehead'>编号</td><td class='tablehead'>姓名</td><td class='tablehead'>性别</td><td class='tablehead'>电话</td><td class='tablehead'>地址</td><td class='tablehead'>星座</td><td class='tablehead' colspan='2'>操作</td></tr>";
 51            
 52            for(var key in data)
 53            {
 54                tableFormat+="<tr><td>"+data[key].id+"</td><td>"+data[key].name+"</td><td>"+data[key].sex+"</td><td>"+data[key].phone+"</td><td>"+data[key].address+"</td><td>"
 55                +data[key].constellation+"</td><td><a target='"+data[key].id+"' title='修改' οnclick='openedit(this)'><img src='img/edit.jpg'></a></td><td><a target='"+data[key].id+"' title='删除' οnclick='opendel(this)'><img src='img/del.jpg' ></a></td></tr>";
 56            }
 57            tableFormat+="</table>";
 58            document.getElementById("showout").innerHTML=tableFormat;
 59        }
 60        else
 61        {
 62            document.getElementById("showout").innerHTML="AJAX Server error!"; 
 63        }      
 64      }
 65 }
 66 
 67 function httpPut(url, method, data)
 68 {    
 69     if(xmlhttp==null)
 70      getHttpRequest();
 71      xmlhttp.open(method,url,true);
 72      xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 73      xmlhttp.setRequestHeader("Content-Length", data.length);
 74      xmlhttp.onreadystatechange=putCallback;
 75      xmlhttp.send(data);
 76 }
 77  
 78 function putCallback()
 79 {    
 80      var panel=document.getElementById("showsuccess");
 81      if (xmlhttp.readyState==4) 
 82      {  
 83          if(xmlhttp.Status >=400 && xmlhttp.Status <=599)
 84            panel.innerHTML="Error Occurred : "& xmlhttp.Status & "-" & xmlhttp.statusText;
 85          else
 86            {
 87              panel.innerHTML=xmlhttp.responseText;
 88              httpGet("myServlet", "GET", "");
 89            }
 90          
 91          setTimeout(hideinfo,1000);
 92      }
 93 }
 94 
 95 function  httpPost(url, method, data)
 96 {
 97     if(xmlhttp==null)
 98      getHttpRequest();
 99      xmlhttp.open(method,url,true);
100      xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
101      xmlhttp.setRequestHeader("Content-Length",data.length);
102      xmlhttp.onreadystatechange=postCallback;
103      xmlhttp.send(data);                                                                                       
104 }
105 
106 function postCallback()
107 {    
108      var panel=document.getElementById("showsuccess");
109      if(xmlhttp.readyState==4)
110      {  
111        if(xmlhttp.status==200)
112        {
113            if(xmlhttp.Status >=400 && xmlhttp.Status <=599)
114              panel.innerHTML="Error Occurred : "& xmlhttp.Status & "-" & xmlhttp.statusText;
115            else
116              {
117                panel.innerHTML=xmlhttp.responseText; 
118                httpGet("myServlet", "GET", "");
119              }
120            setTimeout(hideinfo,1000);
121        }
122       }
123 }
124 
125 function httpDelete(url, method, data)
126 {    
127     if(xmlhttp==null)
128      getHttpRequest();
129      xmlhttp.open(method,url+"?"+data,true);
130      xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
131      xmlhttp.setRequestHeader("Content-Length", data.length);
132      xmlhttp.onreadystatechange=deleteCallback;
133      xmlhttp.send(null); 
134 }
135 
136 function deleteCallback()
137 {
138      if (xmlhttp.readyState==4) 
139      {   
140          if(xmlhttp.Status >=400 && xmlhttp.Status <=599)
141              document.getElementById("showsuccess").innerHTML="Error Occurred : "& xmlhttp.Status & "-" & xmlhttp.statusText;
142          else
143          {
144              document.getElementById("showsuccess").innerHTML=xmlhttp.responseText;    
145              httpGet("myServlet", "GET", "");
146          }
147          setTimeout(hideinfo,1000);
148      }    
149 }
150 
151 function getAjaxJson()
152 {   
153   httpGet("myServlet", "GET", ""); 
154 }
155 
156 function addAjaxJson()
157 {
158  var panel=document.getElementById("addpanel");
159  document.getElementById("title").innerHTML="增加学生信息选项卡";
160  panel.style.top='50px';
161  panel.style.left='200px';
162  panel.style.display='block';
163  document.getElementById("addedit").value="提交";
164  flag=true;
165 }
166 
167 function closepanel()
168 {   
169   document.getElementById("addpanel").style.display='none';
170 }
171 
172 function addrecord()
173 {   
174     var panel=document.getElementById("showsuccess");
175     var s= new Object();
176     s.Id=id;
177     s.Name=document.getElementById("name").value;
178     s.Sex=document.getElementById("sex").value;
179     s.Phone=document.getElementById("tel").value;
180     s.Address=document.getElementById("address").value;
181     s.Constellation=document.getElementById("star").value;
182     if(s.Name=="")
183     {
184         panel.innerHTML="学生姓名不能为空";
185         setTimeout(hideinfo,1000);
186         return;
187     }
188     if(s.Sex=="")
189     {
190         panel.innerHTML="学生性别不能为空";
191         setTimeout(hideinfo,1000);
192         return;
193     }
194     
195     if(s.Phone=="")
196     {
197         panel.innerHTML="学生电话不能为空";
198         setTimeout(hideinfo,1000);
199         return;
200     }
201     if(s.Address=="")
202     {
203         panel.innerHTML="学生家庭不能为空";
204         setTimeout(hideinfo,1000);
205         return;
206     }
207     if(s.Constellation=="")
208     {
209         panel.innerHTML="学生星座不能为空";
210         setTimeout(hideinfo,1000);
211         return;
212     }
213     var data= JSON.stringify(s);
214     if(flag==true) 
215     {
216       httpPut("myServlet","PUT",data);
217     }
218     else
219     {
220       httpPost("myServlet","POST",data);
221     }
222 }
223 
224 function openedit(obj)
225 {
226      var panel=document.getElementById("addpanel");
227      document.getElementById("title").innerHTML="更新学生信息选项卡";
228      panel.style.top='50px';
229      panel.style.left='200px';
230      panel.style.display='block';
231      document.getElementById("addedit").value="保存";
232      for(var key in data)
233      {
234         if(data[key].id==obj.target)
235         {   
236             id=data[key].id;
237             document.getElementById("name").value=data[key].name;
238             document.getElementById("sex").value=data[key].sex;
239             document.getElementById("tel").value=data[key].phone;
240             document.getElementById("address").value=data[key].address;
241             document.getElementById("star").value=data[key].constellation;
242             break;
243         }
244      }     
245      flag=false;
246 }
247 
248 function opendel(obj)
249 {    
250   var mid=null;
251   for(var key in data)
252   {
253    if(data[key].id==obj.target)
254    {  
255      mid=data[key].id;
256      break;
257    }
258   }    
259  if(confirm("你确定要删除数据吗?"))
260  httpDelete("myServlet","DELETE","id="+mid);
261 }
262 
263 function hideinfo()
264 {
265     document.getElementById("showsuccess").innerHTML='';    
266 }

  

Control层设计:

    设计类 myservlet接受客户端的请求,并调用相应的model来处理请求。

   

View Code
  1 package com;
  2 import java.io.BufferedReader;
  3 import java.io.IOException;
  4 import java.io.PrintWriter;
  5 
  6 import javax.servlet.ServletException;
  7 import javax.servlet.http.HttpServlet;
  8 import javax.servlet.http.HttpServletRequest;
  9 import javax.servlet.http.HttpServletResponse;
 10 import java.util.ArrayList;
 11 import net.sf.json.*;
 12 
 13 public class myServlet extends HttpServlet {
 14     private static final long serialVersionUID=1L;
 15     
 16     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
 17     {
 18         // TODO Auto-generated method stub
 19          //指定 去除客户端页面的缓存
 20          ClearCache(response); 
 21         //将List转化为JSON  
 22         ArrayList<UserModel> list=Mysql.queryUserList();
 23         //设置编码   
 24         response.setCharacterEncoding("utf-8");
 25         //写入到前台   
 26         JSONArray json1=JSONArray.fromObject(list);
 27         response.getWriter().write(json1.toString());
 28         //System.out.print(json1.toString());
 29         response.getWriter().flush();
 30         response.getWriter().close();
 31      }
 32      
 33     public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
 34     {
 35         //清除页面缓存
 36          ClearCache(response);
 37          BufferedReader sis = request.getReader(); 
 38          String data=new String(sis.readLine().getBytes("iso-8859-1"),"utf-8");
 39          //System.out.println(data); 
 40          JSONObject json =JSONObject.fromObject(data);
 41          //插入数据库
 42          boolean add=Mysql.addRecord(createUserbyjson(json,1));
 43          
 44          response.setContentType("text/html");
 45          response.setCharacterEncoding("utf-8");
 46          PrintWriter out=response.getWriter();
 47          if(add==true)
 48              out.write("数据提交成功!");
 49          else
 50              out.write("数据提交失败!"); 
 51          out.flush(); 
 52          out.close();
 53     }
 54     
 55     
 56      
 57     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
 58         {
 59             //清除页面缓存
 60              ClearCache(response);
 61              BufferedReader sis = request.getReader(); 
 62              String data=new String(sis.readLine().getBytes("iso-8859-1"),"utf-8");
 63              //System.out.println(data); 
 64              JSONObject json =JSONObject.fromObject(data);
 65              //修改数据库
 66              boolean edit=Mysql.updateRecord(createUserbyjson(json,2)); 
 67              response.setContentType("text/html");
 68              response.setCharacterEncoding("utf-8");
 69              PrintWriter out=response.getWriter();
 70              if(edit==true)
 71                  out.write("数据修改成功!");
 72              else
 73                  out.write("数据修改失败!"); 
 74              out.flush(); 
 75              out.close();
 76         }
 77      
 78      
 79     public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
 80         {
 81             //清除页面缓存
 82            request.setCharacterEncoding("utf-8");
 83            String  id=new String((request.getParameter("id")).getBytes("iso-8859-1"));
 84            response.setContentType("text/html");
 85            response.setCharacterEncoding("utf-8");
 86            PrintWriter out=response.getWriter();
 87            //System.out.println(id);
 88            boolean del=Mysql.deleteRecord(Integer.parseInt(id));
 89              if(del==true)
 90                  out.write("数据删除成功!");
 91              else
 92                  out.write("数据删除失败!"); 
 93              out.flush(); 
 94              out.close();
 95         }
 96     private UserModel createUserbyjson(JSONObject json,int optype)
 97      {
 98          UserModel um=new UserModel();
 99         //修改时才要ID
100          if(optype==2)
101          um.setId(json.getInt("Id"));
102          um.setName(json.getString("Name"));
103          um.setSex(json.getString("Sex"));
104          um.setPhone(json.getString("Phone"));
105          um.setAddress(json.getString("Address"));
106          um.setConstellation(json.getString("Constellation"));
107          return um;
108      }
109      
110     private void ClearCache(HttpServletResponse response)
111      {
112         //指定 去除客户端页面的缓存
113         response.setHeader("pragma", "no-cache");
114         response.setHeader("cache-control", "no-cache");
115         response.setHeader("expires", "0"); 
116      }
117 }

Model层设计:

 设计Mysql类来访问DB,进行数据处理,然后把数据返回调用的Control层。

 

View Code
  1 package com;
  2 import java.sql.*;
  3 import java.util.ArrayList;
  4 public class Mysql
  5 {
  6       //jdbc driver name
  7     private static final String driverName= "com.mysql.jdbc.Driver";    
  8     // path for database
  9     private static final String dbURL= "jdbc:mysql://localhost:3306/ontology?useUnicode=true&characterEncoding=utf-8";    
 10     //username 
 11     private static final String userName= "root";    
 12     //password
 13     private static final String userPwd= "sql123";    
 14     
 15     private static Connection conn=null;
 16     private static PreparedStatement ps=null;
 17     public static Connection getConn()
 18     {
 19         try
 20         {
 21             Class.forName(driverName);
 22             conn=DriverManager.getConnection(dbURL,userName,userPwd);    
 23             return conn;
 24         }
 25         catch(Exception e)
 26         {
 27             e.printStackTrace();
 28             return null;
 29         }
 30         
 31     }
 32     
 33     public static boolean closeConn()
 34     {
 35         try
 36         {
 37             conn.close();
 38             return true;
 39         }
 40         catch(Exception e)
 41         {
 42             e.printStackTrace();
 43             return false;
 44         }
 45         
 46     }
 47     public static PreparedStatement getSqlPreparedStatement(String sql)
 48     {   
 49         try
 50         {
 51         ps=conn.prepareStatement(sql);
 52         return ps;
 53         }
 54         catch(Exception e)
 55         {
 56           e.printStackTrace();
 57           return null;
 58         }
 59         
 60     }
 61     
 62     public static boolean addRecord(UserModel um)
 63     {   
 64         String sql="insert into people(username,sex,phone,address,constellation) values(?,?,?,?,?)";
 65         try
 66         {   getConn();
 67             getSqlPreparedStatement(sql);
 68             ps.setString(1,um.getName());
 69             ps.setString(2, um.getSex());
 70             ps.setString(3, um.getPhone());
 71             ps.setString(4, um.getAddress());
 72             ps.setString(5, um.getConstellation());
 73             
 74             int row=ps.executeUpdate();
 75             if(row>0)
 76             {
 77                 ps.close();
 78                 closeConn();
 79                 return true;
 80             }
 81             else
 82              return false;
 83         }
 84         catch(Exception e)
 85         {
 86             e.printStackTrace();
 87             return false;
 88         }
 89         
 90     }
 91     
 92     
 93     public static boolean updateRecord(UserModel um)
 94     {   
 95         String sql="update people set username=?,sex=?,phone=?,address=?,constellation=? where userid=?";
 96         try
 97         {   getConn();
 98             getSqlPreparedStatement(sql);
 99             ps.setString(1,um.getName());
100             ps.setString(2, um.getSex());
101             ps.setString(3, um.getPhone());
102             ps.setString(4, um.getAddress());
103             ps.setString(5, um.getConstellation());
104             ps.setInt(6, um.getId());
105             System.out.print(um.getId());
106             int row=ps.executeUpdate();
107             if(row>0)
108             {
109                 ps.close();
110                 closeConn();
111                 return true;
112             }
113             else
114              return false;
115         }
116         catch(Exception e)
117         {
118             e.printStackTrace();
119             return false;
120         }
121         
122     }
123     
124     public static boolean deleteRecord(int id)
125     {   
126         String sql="delete from people where userid=?";
127         try
128         {   getConn();
129             getSqlPreparedStatement(sql);
130             ps.setInt(1,id);
131             int row=ps.executeUpdate();
132             if(row>0)
133             {
134                 ps.close();
135                 closeConn();
136                 return true;
137             }
138             else
139              return false;
140         }
141         catch(Exception e)
142         {
143             e.printStackTrace();
144             return false;
145         }
146         
147     }
148     
149     public static ArrayList<UserModel> queryUserList()
150     {   
151         String sql="select * from people";
152         try
153         {   getConn();
154             Statement stm=conn.createStatement();
155             ResultSet rs=stm.executeQuery(sql);
156             ArrayList<UserModel> list=new ArrayList<UserModel>();
157             while(rs.next())
158             {
159                   UserModel user1=new UserModel();
160                     user1.setId(rs.getInt("userid")); 
161                     user1.setName(rs.getString("username"));
162                     user1.setSex(rs.getString("sex"));
163                     user1.setPhone(rs.getString("phone"));
164                     user1.setAddress(rs.getString("address"));
165                     user1.setConstellation(rs.getString("constellation"));
166                     list.add(user1);     
167             }
168             rs.close();
169             stm.close();
170             closeConn();
171             return list;
172         }
173         catch(Exception e)
174         {
175             e.printStackTrace();
176             return null;
177         }
178     }
179 }

用到自定义类UserModel:

View Code
  1 package com;
  2 import java.util.ArrayList;
  3 
  4 public class UserModel
  5 {
  6     /**
  7      * @param args
  8      */
  9     private int Id;
 10     private String Name;
 11     private String Sex;
 12     private String Phone;
 13     private String Address;
 14     private String Constellation;
 15     public UserModel()
 16     { }
 17     /**
 18      * @return the id
 19      */
 20     public int getId()
 21     {
 22         return Id;
 23     }
 24     /**
 25      * @param id the id to set
 26      */
 27     public void setId(int id)
 28     {
 29         Id = id;
 30     }
 31     /**
 32      * @return the name
 33      */
 34     public String getName() 
 35     {
 36         return Name;
 37     }
 38     /**
 39      * @param name the name to set
 40      */
 41     public void setName(String name)
 42     {
 43         Name = name;
 44     }
 45     /**
 46      * @return the sex
 47      */
 48     public String getSex()
 49     {
 50         return Sex;
 51     }
 52     /**
 53      * @param sex the sex to set
 54      */
 55     public void setSex(String sex)
 56     {
 57         Sex = sex;
 58     }
 59     /**
 60      * @return the phone
 61      */
 62     public String getPhone()
 63     {
 64         return Phone;
 65     }
 66     /**
 67      * @param phone the phone to set
 68      */
 69     public void setPhone(String phone)
 70     {
 71         Phone = phone;
 72     }
 73     /**
 74      * @return the address
 75      */
 76     public String getAddress()
 77     {
 78         return Address;
 79     }
 80     /**
 81      * @param address the address to set
 82      */
 83     public void setAddress(String address) 
 84     {
 85         Address = address;
 86     }
 87     /**
 88      * @return the constellation
 89      */
 90     public String getConstellation() 
 91     {
 92         return Constellation;
 93     }
 94     /**
 95      * @param constellation the constellation to set
 96      */
 97     public void setConstellation(String constellation)
 98     {
 99         Constellation = constellation;
100     }
101     
102     public static ArrayList<UserModel> getUserlist()
103     {
104            ArrayList<UserModel> list=new ArrayList<UserModel>();   
105             
106             for(int i=1;i<=20;++i)
107             {
108                   UserModel user1=new UserModel();//�û�����1  
109                     user1.setId(i); 
110                     if(i%2==0)
111                     {
112                         user1.setName("��"+i);   
113                         user1.setSex("Ů");    
114                     }
115                     else
116                     {
117                         user1.setName("����"+i);   
118                         user1.setSex("��");
119                     }
120                     user1.setPhone("029-8623"+i);
121                     user1.setAddress("�人����ѧ�����ѧԺ");
122                     user1.setConstellation("����"+i);
123                     list.add(user1); 
124             }
125              
126             return list;  
127     }
128 }

 最后效果:

 

转载本文请标明出处。

转载于:https://www.cnblogs.com/cxtczzy/archive/2012/12/29/2838986.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值