`
huiqinbo
  • 浏览: 335718 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

通过Servlet让Extjs GridPanel 显示数据库数据

阅读更多

文章分类:Web前端

GridPanel上显示数据,可以使用Struts,也可以使用Servlet的方法,两者的用法相近,所以,给出后者的实现方法:

 

这里先列出HTML代码:

 

Html代码 复制代码
  1. <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>  
  2. <%   
  3. String path = request.getContextPath();   
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";   
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   
  10.   <head>  
  11.     <link rel="stylesheet" type="text/css" href="../resources/css/ext-all.css" />  
  12.     <script type="text/javascript" src="../adapter/ext/ext-base.js"></script>    
  13.     <script type="text/javascript" src="../js/ext-all-debug.js"></script>  
  14.        
  15.     <link rel="stylesheet" type="text/css" href="../css/grid-examples.css" />  
  16.     <link rel="stylesheet" type="text/css" href="../css/examples.css" />  
  17.      <link rel="stylesheet" type="text/css" href="css/styles.css" />  
  18.      <title>后台登陆页面</title>  
  19.   
  20.   </head>  
  21.          
  22.   <body>  
  23.     <script type="text/javascript" src="../css/examples.js"></script>  
  24.        
  25.     <script type="text/javascript">  
  26.        
  27.     Ext.onReady(function(){   
  28.   
  29.          var win;   
  30.          var button = Ext.get('show-btn');   
  31.   
  32.          button.on('click', function(){   
  33.              // create the window on the first click and reuse on subsequent clicks   
  34.              if(!win){   
  35.                  win = new Ext.Window({   
  36.                      applyTo:'hello-win',   
  37.                      layout:'fit',   
  38.                      width:500,   
  39.                      height:500,   
  40.                      closeAction:'hide',   
  41.                      plain: true,   
  42.   
  43.                      items: new Ext.TabPanel({   
  44.                          applyTo: 'hello-tabs',   
  45.                          autoTabs:true,   
  46.                          activeTab:0,   
  47.                          deferredRender:false,   
  48.                          border:false,   
  49.                          items : [ {   
  50.   
  51.                             title : '添加操作',   
  52.   
  53.                             html : '<iframe width=100height=100src=address_add.jsp />'   
  54.                                
  55.                         } ]   
  56.                      })   
  57.   
  58.                  });   
  59.              }   
  60.              win.show(this);   
  61.          });   
  62.            
  63.   
  64.         //下面是做列表(原来是通过HttpProxy和Servlet来实现JS与数据库数据的交互)   
  65.   
  66.          var store = new Ext.data.JsonStore({   
  67.              root: 'bugs',   
  68.              totalProperty: 'totalCount',   
  69.              idProperty: 'threadid',   
  70.              remoteSort: true,   
  71.   
  72.              fields: ['id','name','sex','mobile','email','qq','company','address','postcode'],   
  73.   
  74.              proxy: new Ext.data.HttpProxy({     
  75.                  //url:'http://localhost:8080/ExtjsPaging/Bug',     
  76.                  url:'http://localhost:8080/Jstudio_v1_0029_extjs_jsp/DataServlet',   
  77.                  method:'GET'     
  78.              })     
  79.          });   
  80.          store.setDefaultSort('id', 'desc');   
  81.   
  82.   
  83.            
  84.             
  85.   
  86.          var grid = new Ext.grid.GridPanel({   
  87.              width:"100%",   
  88.              height:550,   
  89.              title:'通讯录列表',   
  90.              store: store,   
  91.              trackMouseOver:false,   
  92.              disableSelection:false,   
  93.              loadMask: true,   
  94.   
  95.              // grid columns   
  96.              columns:[{   
  97.                  header: "序号",   
  98.                  dataIndex: 'id',   
  99.                  width: 70,   
  100.                  align: 'center',   
  101.                 // renderer: renderTopic,   
  102.                  sortable: true   
  103.              },{   
  104.                  header: "姓名",   
  105.                  dataIndex: 'name',   
  106.                  width: 100,   
  107.                  align: 'center',   
  108.                  //hidden: true,   
  109.                  sortable: true   
  110.              },{   
  111.                  header: "性别",   
  112.                  dataIndex: 'sex',   
  113.                  width: 70,   
  114.                  align: 'center',   
  115.                  //sortable: true   
  116.              },{   
  117.                  //id: 'mobile',   
  118.                  header: "手机号码",   
  119.                  dataIndex: 'mobile',   
  120.                  width: 200,   
  121.                  align: 'center',   
  122.                  //renderer: renderLast,   
  123.                 // sortable: true   
  124.              },{   
  125.                  header: "电子邮件",   
  126.                  dataIndex: 'email',   
  127.                  width: 200,   
  128.                  align: 'center',   
  129.                 // sortable: true   
  130.              },{   
  131.                  header: "QQ号码",   
  132.                  dataIndex: 'qq',   
  133.                  width: 200,   
  134.                  align: 'center',   
  135.                 // sortable: true   
  136.              },{   
  137.                  header: "公司名称",   
  138.                  dataIndex: 'company',   
  139.                  width: 200,   
  140.                  align: 'center',   
  141.                 // sortable: true   
  142.              },{   
  143.                  header: "地址",   
  144.                  dataIndex: 'address',   
  145.                  width: 300,   
  146.                  align: 'center',   
  147.                 // sortable: true   
  148.              },{   
  149.                  header: "邮编",   
  150.                  dataIndex: 'postcode',   
  151.                  width: 100,   
  152.                  align: 'center',   
  153.                 // sortable: true   
  154.              }   
  155.              ],   
  156.   
  157.              // customize view config   
  158.              viewConfig: {   
  159.                  forceFit:true,   
  160.                  enableRowBody:true,   
  161.                  showPreview:false,   
  162.                  getRowClass : function(record, rowIndex, p, store){   
  163.                      if(this.showPreview){   
  164.                          p.body = '<p>'+record.data.excerpt+'</p>';   
  165.                          return 'x-grid3-row-expanded';   
  166.                      }   
  167.                      return 'x-grid3-row-collapsed';   
  168.                  }   
  169.              },   
  170.   
  171.              // paging bar on the bottom   
  172.              bbar: new Ext.PagingToolbar({   
  173.                  pageSize: 25,   
  174.                  store: store,   
  175.                  displayInfo: true,   
  176.                  displayMsg: 'Displaying topics {0} - {1} of {2}',   
  177.                  emptyMsg: "No topics to display",   
  178.                  items:[   
  179.                      '-', {   
  180.                      pressed: true,   
  181.                      enableToggle:true,   
  182.                      text: 'Show Preview',   
  183.                      cls: 'x-btn-text-icon details',   
  184.                      toggleHandler: function(btn, pressed){   
  185.                          var view = grid.getView();   
  186.                          view.showPreview = pressed;   
  187.                          view.refresh();   
  188.                      }   
  189.                  }]   
  190.              })   
  191.          });   
  192.   
  193.          // render it   
  194.          grid.render('topic-grid');   
  195.   
  196.          // trigger the data store load   
  197.          store.load({params:{start:0, limit:25}});   
  198.           
  199.     });   
  200.     </script>  
  201.        
  202.        
  203.   
  204.      <input type="button" id="show-btn" value="添加联系人" /><br /><br />  
  205.     <div id="hello-win" class="x-hidden">  
  206.     <div class="x-window-header">Hello Dialog</div>  
  207.     <div id="hello-tabs"></div>  
  208. </div>  
  209.   
  210.         
  211.       
  212.           <div id="topic-grid"></div>  
  213.       
  214.      
  215.           
  216.           
  217.           
  218.   </body>  
  219. </html>  
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>

  <head>
    <link rel="stylesheet" type="text/css" href="../resources/css/ext-all.css" />
	<script type="text/javascript" src="../adapter/ext/ext-base.js"></script> 
	<script type="text/javascript" src="../js/ext-all-debug.js"></script>
	
    <link rel="stylesheet" type="text/css" href="../css/grid-examples.css" />
    <link rel="stylesheet" type="text/css" href="../css/examples.css" />
     <link rel="stylesheet" type="text/css" href="css/styles.css" />
     <title>后台登陆页面</title>

  </head>
      
  <body>
    <script type="text/javascript" src="../css/examples.js"></script>
    
    <script type="text/javascript">
    
    Ext.onReady(function(){

    	 var win;
         var button = Ext.get('show-btn');

         button.on('click', function(){
             // create the window on the first click and reuse on subsequent clicks
             if(!win){
                 win = new Ext.Window({
                     applyTo:'hello-win',
                     layout:'fit',
                     width:500,
                     height:500,
                     closeAction:'hide',
                     plain: true,

                     items: new Ext.TabPanel({
                         applyTo: 'hello-tabs',
                         autoTabs:true,
                         activeTab:0,
                         deferredRender:false,
                         border:false,
                         items : [ {

             				title : '添加操作',

             				html : '<iframe width=100% height=100% src=address_add.jsp />'
             				
             			} ]
                     })

                 });
             }
             win.show(this);
         });
        

    	//下面是做列表(原来是通过HttpProxy和Servlet来实现JS与数据库数据的交互)

         var store = new Ext.data.JsonStore({
             root: 'bugs',
             totalProperty: 'totalCount',
             idProperty: 'threadid',
             remoteSort: true,

             fields: ['id','name','sex','mobile','email','qq','company','address','postcode'],

             proxy: new Ext.data.HttpProxy({  
                 //url:'http://localhost:8080/ExtjsPaging/Bug',  
                 url:'http://localhost:8080/Jstudio_v1_0029_extjs_jsp/DataServlet',
                 method:'GET'  
             })  
         });
         store.setDefaultSort('id', 'desc');


        
         

         var grid = new Ext.grid.GridPanel({
             width:"100%",
             height:550,
             title:'通讯录列表',
             store: store,
             trackMouseOver:false,
             disableSelection:false,
             loadMask: true,

             // grid columns
             columns:[{
                 header: "序号",
                 dataIndex: 'id',
                 width: 70,
                 align: 'center',
                // renderer: renderTopic,
                 sortable: true
             },{
                 header: "姓名",
                 dataIndex: 'name',
                 width: 100,
                 align: 'center',
                 //hidden: true,
                 sortable: true
             },{
                 header: "性别",
                 dataIndex: 'sex',
                 width: 70,
                 align: 'center',
                 //sortable: true
             },{
                 //id: 'mobile',
                 header: "手机号码",
                 dataIndex: 'mobile',
                 width: 200,
                 align: 'center',
                 //renderer: renderLast,
                // sortable: true
             },{
                 header: "电子邮件",
                 dataIndex: 'email',
                 width: 200,
                 align: 'center',
                // sortable: true
             },{
                 header: "QQ号码",
                 dataIndex: 'qq',
                 width: 200,
                 align: 'center',
                // sortable: true
             },{
                 header: "公司名称",
                 dataIndex: 'company',
                 width: 200,
                 align: 'center',
                // sortable: true
             },{
                 header: "地址",
                 dataIndex: 'address',
                 width: 300,
                 align: 'center',
                // sortable: true
             },{
                 header: "邮编",
                 dataIndex: 'postcode',
                 width: 100,
                 align: 'center',
                // sortable: true
             }
             ],

             // customize view config
             viewConfig: {
                 forceFit:true,
                 enableRowBody:true,
                 showPreview:false,
                 getRowClass : function(record, rowIndex, p, store){
                     if(this.showPreview){
                         p.body = '<p>'+record.data.excerpt+'</p>';
                         return 'x-grid3-row-expanded';
                     }
                     return 'x-grid3-row-collapsed';
                 }
             },

             // paging bar on the bottom
             bbar: new Ext.PagingToolbar({
                 pageSize: 25,
                 store: store,
                 displayInfo: true,
                 displayMsg: 'Displaying topics {0} - {1} of {2}',
                 emptyMsg: "No topics to display",
                 items:[
                     '-', {
                     pressed: true,
                     enableToggle:true,
                     text: 'Show Preview',
                     cls: 'x-btn-text-icon details',
                     toggleHandler: function(btn, pressed){
                         var view = grid.getView();
                         view.showPreview = pressed;
                         view.refresh();
                     }
                 }]
             })
         });

         // render it
         grid.render('topic-grid');

         // trigger the data store load
         store.load({params:{start:0, limit:25}});
       
    });
    </script>
    
    

     <input type="button" id="show-btn" value="添加联系人" /><br /><br />
    <div id="hello-win" class="x-hidden">
    <div class="x-window-header">Hello Dialog</div>
    <div id="hello-tabs"></div>
</div>

     
   
          <div id="topic-grid"></div>
   
  
       
       
       
  </body>
</html>

 

然后给出实现Servlet类

 

Java代码 复制代码
  1. package com.lee.servlet;   
  2.   
  3. import java.io.IOException;   
  4. import java.io.PrintWriter;   
  5. import java.util.Hashtable;   
  6. import java.util.Iterator;   
  7. import java.util.List;   
  8.   
  9. import javax.servlet.ServletException;   
  10. import javax.servlet.http.HttpServlet;   
  11. import javax.servlet.http.HttpServletRequest;   
  12. import javax.servlet.http.HttpServletResponse;   
  13.   
  14. import com.lee.dao.ServletDao;   
  15.   
  16. public class DataServlet extends HttpServlet {   
  17.   
  18.     @Override  
  19.     protected void doGet(HttpServletRequest request, HttpServletResponse response)   
  20.             throws ServletException, IOException {   
  21.            
  22.             
  23.          
  24.             String sql = "select * from address";     
  25.          
  26.            ServletDao sd = new ServletDao();   
  27.            List<Hashtable<String, String>> list2 = sd.selectData(sql);    
  28.            Iterator<Hashtable<String, String>> it = list2.iterator();   
  29.          
  30.               
  31.               
  32.               
  33.             StringBuilder sb = new StringBuilder();     
  34.             sb.append("{totalCount:14,bugs:[");     
  35.                
  36.             while(it.hasNext()) {   
  37.                     
  38.                  Hashtable<String, String> hash2 = it.next();   
  39.                     
  40.                  //String name2 = hash2.get("qq");   
  41.                     
  42.                
  43.                 sb.append("{");     
  44.                 sb.append("id:" + hash2.get("id"));     
  45.                 sb.append(",name:" + "\'" + hash2.get("name") + "\'");     
  46.                 sb.append(",sex:" + "\'" + hash2.get("sex") + "\'");    
  47.                 sb.append(",mobile:" + "\'" + hash2.get("mobile") + "\'");    
  48.                 sb.append(",email:" + "\'" + hash2.get("email") + "\'");    
  49.                 sb.append(",qq:" + "\'" + hash2.get("qq") + "\'");    
  50.                 sb.append(",company:" + "\'" + hash2.get("company") + "\'");    
  51.                 sb.append(",address:" + "\'" + hash2.get("address") + "\'");   
  52.                 sb.append(",postcode:" + "\'" + hash2.get("postcode") + "\'");    
  53.                 sb.append("},");     
  54.          
  55.                
  56.                
  57.                
  58.             }   
  59.             String json = sb.substring(0, sb.length() - 1);     
  60.             json += "]}";     
  61.             response.setContentType("text/html");     
  62.             response.setCharacterEncoding("UTF-8");     
  63.             PrintWriter out = response.getWriter();     
  64.             out.println(json);     
  65.             out.close();     
  66.            
  67.            
  68.     }   
  69.   
  70.     @Override  
  71.     protected void doPost(HttpServletRequest request, HttpServletResponse response)   
  72.             throws ServletException, IOException {   
  73.            
  74.         doGet(request, response);   
  75.     }   
  76.   
  77. }  
package com.lee.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lee.dao.ServletDao;

public class DataServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		 
	  
	        String sql = "select * from address";  
	  
	       ServletDao sd = new ServletDao();
	       List<Hashtable<String, String>> list2 = sd.selectData(sql); 
	       Iterator<Hashtable<String, String>> it = list2.iterator();
	  
	       
	       
	       
	        StringBuilder sb = new StringBuilder();  
	        sb.append("{totalCount:14,bugs:[");  
	        
	        while(it.hasNext()) {
	        	 
	        	 Hashtable<String, String> hash2 = it.next();
	        	 
	        	 //String name2 = hash2.get("qq");
	        	 
	        
	            sb.append("{");  
	            sb.append("id:" + hash2.get("id"));  
	            sb.append(",name:" + "\'" + hash2.get("name") + "\'");  
	            sb.append(",sex:" + "\'" + hash2.get("sex") + "\'"); 
	            sb.append(",mobile:" + "\'" + hash2.get("mobile") + "\'"); 
	            sb.append(",email:" + "\'" + hash2.get("email") + "\'"); 
	            sb.append(",qq:" + "\'" + hash2.get("qq") + "\'"); 
	            sb.append(",company:" + "\'" + hash2.get("company") + "\'"); 
	            sb.append(",address:" + "\'" + hash2.get("address") + "\'");
	            sb.append(",postcode:" + "\'" + hash2.get("postcode") + "\'"); 
	            sb.append("},");  
	  
	        
	        
	        
	        }
	        String json = sb.substring(0, sb.length() - 1);  
	        json += "]}";  
	        response.setContentType("text/html");  
	        response.setCharacterEncoding("UTF-8");  
	        PrintWriter out = response.getWriter();  
	        out.println(json);  
	        out.close();  
		
		
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		doGet(request, response);
	}

}

 

再是 dao层:(内是相关的测试)

 

Java代码 复制代码
  1. package com.lee.dao;   
  2.   
  3. import java.sql.Connection;   
  4. import java.sql.DriverManager;   
  5. import java.sql.ResultSet;   
  6. import java.sql.Statement;   
  7. import java.util.ArrayList;   
  8. import java.util.Hashtable;   
  9. import java.util.Iterator;   
  10. import java.util.List;   
  11. import java.sql.ResultSetMetaData;   
  12.   
  13.   
  14. public class ServletDao {   
  15.   
  16.     public List selectData(String sql) {   
  17.            
  18.         //List<Object> list = new ArrayList<Object>();   
  19.         List<Hashtable<String, String>> list = new ArrayList<Hashtable<String,String>>();   
  20.            
  21.         try {   
  22.             Class.forName("com.mysql.jdbc.Driver");   
  23.             String url = "jdbc:mysql://localhost:3306/ssh_ext_demo";   
  24.             Connection conn = DriverManager.getConnection(url, "root""123");   
  25.             Statement stmt = conn.createStatement();   
  26.             ResultSet rs = stmt.executeQuery(sql);   
  27.             ResultSetMetaData rsmd = rs.getMetaData();   
  28.                
  29.             while(rs.next()) {   
  30.                    
  31.                 Hashtable<String, String> hash =new Hashtable<String, String>();   
  32.                    
  33.                    
  34.                 for(int i =1;i<=rsmd.getColumnCount();i++){   
  35.                      String field = (String)rsmd.getColumnName(i);   
  36.                      String value = (String)rs.getString(i);   
  37.                      if(value == null)   
  38.                          value="";   
  39.                      hash.put(field, value);   
  40.                }   
  41.                    
  42.                 list.add(hash);   
  43.             }   
  44.                
  45.         } catch (Exception e) {   
  46.             e.printStackTrace();   
  47.         }   
  48.         return list;   
  49.            
  50.     }   
  51.        
  52.     public static void main(String[] args) {   
  53.   
  54.         String s = "select * from address";   
  55.         ServletDao sd = new ServletDao();   
  56.            
  57.          List<Hashtable<String, String>> list2 = sd.selectData(s);   
  58.             
  59.          Iterator<Hashtable<String, String>> it = list2.iterator();   
  60.             
  61.          StringBuilder sb = new StringBuilder();     
  62.             sb.append("{totalCount:14,bugs:[");     
  63.                
  64.             while(it.hasNext()) {   
  65.                     
  66.                  Hashtable<String, String> hash2 = it.next();   
  67.                     
  68.                  //String name2 = hash2.get("qq");   
  69.                     
  70.                
  71.                 sb.append("{");     
  72.                 sb.append("id:" + hash2.get("id"));     
  73.                 sb.append(",name:" + "\'" + hash2.get("name") + "\'");     
  74.                 sb.append(",sex:" + "\'" + hash2.get("sex") + "\'");    
  75.                 sb.append(",mobile:" + "\'" + hash2.get("mobile") + "\'");    
  76.                 sb.append(",email:" + "\'" + hash2.get("email") + "\'");    
  77.                 sb.append(",qq:" + "\'" + hash2.get("qq") + "\'");    
  78.                 sb.append(",company:" + "\'" + hash2.get("company") + "\'");    
  79.                 sb.append(",address:" + "\'" + hash2.get("address") + "\'");   
  80.                 sb.append(",postcode:" + "\'" + hash2.get("postcode") + "\'");    
  81.                 sb.append("},");     
  82.          
  83.                
  84.                
  85.                
  86.             }   
  87.             String json = sb.substring(0, sb.length() - 1);     
  88.             json += "]}";     
  89.                
  90.                
  91.          System.out.println(json);   
  92.            
  93.     }   
  94. }  
package com.lee.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.sql.ResultSetMetaData;


public class ServletDao {

	public List selectData(String sql) {
       	
		//List<Object> list = new ArrayList<Object>();
		List<Hashtable<String, String>> list = new ArrayList<Hashtable<String,String>>();
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jd

  


  
0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics