jqGrid(3.6版本) 入门——创建jqGrid表格

       由于jqGrid主要是用来处理和展现动态数据的,所以将创建一个Invoice 信息的数据库表,然后用jqGrid对其进行展现。

注:原例子见jqGrid的官方wiki:http://www.trirand.com/jqgridwiki/doku.php?id=wiki:first_grid,原例子服务器端是PHP的,我改成Jsp的了。)。

 

  在MySql中创建表并插入一些数据。

          DROP TABLE IF EXISTS `invheader`; CREATE TABLE `invheader` ( `invid` int(11) NOT NULL AUTO_INCREMENT, `invdate` date NOT NULL, `client_id` int(11) NOT NULL, `amount` decimal(10,2) NOT NULL DEFAULT '0.00', `tax` decimal(10,2) NOT NULL DEFAULT '0.00', `total` decimal(10,2) NOT NULL DEFAULT '0.00', `note` char(100) DEFAULT NULL, PRIMARY KEY (`invid`) ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8; INSERT INTO `invheader` VALUES ('1', '2009-11-11', '9400001', '10.00', '10.00', '100.00', 'xyz'); INSERT INTO `invheader` VALUES ('2', '2009-11-10', '9400002', '50.00', '50.00', '500.00', 'abc'); INSERT INTO `invheader` VALUES ('3', '2009-11-09', '9400003', '25.00', '25.00', '250.00', 'cba'); INSERT INTO `invheader` VALUES ('4', '2009-11-08', '9400004', '789.00', '0.02', '345.67', 'ccc'); INSERT INTO `invheader` VALUES ('5', '2009-11-07', '9400005', '8976.00', '0.11', '543.34', 'hhh'); INSERT INTO `invheader` VALUES ('6', '2009-11-06', '9400006', '5678.00', '0.56', '890.76', 'ggg'); INSERT INTO `invheader` VALUES ('7', '2009-11-05', '9400007', '4567.00', '0.74', '314.67', 'eee'); INSERT INTO `invheader` VALUES ('8', '2009-11-04', '9400008', '5789.00', '0.23', '234.56', 'fff'); INSERT INTO `invheader` VALUES ('9', '2009-11-03', '9400009', '5000.00', '0.43', '765.89', 'ddd'); INSERT INTO `invheader` VALUES ('10', '2009-11-02', '9400010', '4000.00', '0.78', '654.45', 'ccc'); INSERT INTO `invheader` VALUES ('11', '2009-11-01', '9400011', '1000.00', '0.25', '78.65', 'bbb'); INSERT INTO `invheader` VALUES ('12', '2009-10-11', '9400012', '500.00', '0.01', '58.90', 'aaa');

 

表格列的说明:

  • Invid - 发票key;
  • invdate - 发票日期;
  • amount - 数额;
  • tax        - 税率;
  • total     - 总额(包含税);
  • note     - 备注;

接着创建JSP页面,如下:

    

       <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% 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> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <link type="text/css" href="<%=basePath%>css/redmond/jquery-ui-1.7.2.custom.css" rel="Stylesheet" /> <link rel="stylesheet" type="text/css" media="screen" href="<%=basePath%>css/ui.jqgrid.css"/> <mce:script type="text/javascript" src="<%=basePath%><!-- js/jquery-1.3.2.min.js"> // --></mce:script> <mce:script type="text/javascript" src="<%=basePath%><!-- js/jquery-ui-1.7.2.custom.min.js"> // --></mce:script> <mce:script type="text/javascript" src="<%=basePath%><!-- js/i18n/grid.locale-zh.js"> // --></mce:script> <mce:script type="text/javascript" src="<%=basePath%><!-- js/jquery.jqGrid.min.js"> // --></mce:script> <mce:script type="text/javascript"><!-- jQuery(document).ready(function(){ jQuery("#myfisttbl").jqGrid({ url:'servlet/ShowData', autowidth:true, datatype: 'xml', mtype: 'GET', colNames:['发票号码','出具日期', '金额','税率','总额','备注'], colModel :[ {name:'invid', index:'invid', width:55}, {name:'invdate', index:'invdate', width:90}, {name:'amount', index:'amount', width:80, align:'right'}, {name:'tax', index:'tax', width:80, align:'right'}, {name:'total', index:'total', width:80, align:'right'}, {name:'note', index:'note', width:150, sortable:false} ], pager: '#tblbar', rowNum:10, rowList:[10,20,30], sortname: 'invid', sortorder: 'desc', viewrecords: true, caption: '我的第一个表格' }); }); // --></mce:script> </head> <body> <table id="myfisttbl"></table> <div id="tblbar"></div> </body> </html>

 

到这里前台的工作已经完成了。其实现在已经可以访问这个页面,在我的项目中他是index.jsp页面,所以访问的地址是:

http://localhost:8080/TestJqtable/(tomcat发布)如图:

 

 

 

 

 

可以看到此时表格已经显示出来只是没有数据,因为服务器端得代码还没有写。下面来完成服务器端的代码。

 

服务器端代码主要就是连接数据库读取invheader表格的数据,这和通常的基于java的web程序没有什么不同,我写了个ShowData类,该类是个表准的servlet在该类的doGet方法中进行数据读取。不过需要注意的是,servelet返回数据的格式。由于jqGrid可以处理多种格式的数据,如xml,json等,但默认情况下jqGrid接收xml格式的数据,这个例子里 datatype: 'xml', mtype: 'GET'这两设置说了jqGrid会用get请求去访问服务端,读取服务器端返回的xml格式的数据。默认的xml格式如下:

 

 

                                          <?xml version ="1.0" encoding="utf-8"?> <rows> <page> </page> <total> </total> <records> </records> <row id = 'unique_rowid'> <cell> cellcontent </cell> <cell> <!--[CDATA[<font color='red'>cell</font> content]]> </cell> … </row> <row id = 'unique_rowid'> <cell> cellcontent </cell> <cell> <![CDATA[<font color='red'>cell</font> content]]--> </cell> … </row> … </rows>

 

  

 因此当servlet从数据库读取数据后需要将读取的数据按此格式进行拼装,然后将结果发送给jqGrid,jqGrid接收后将数据展现出来。

 为了实习此功能,我将连接DataBase和装配xml文件的功能分成两个类DBUtil类负责连接数据库以javaBean(DataBean)的形式返回数据列表,CreateXml类,作用为以上述默认形式返回xml字符串,CreateXml调用DBUtil方法取得数据,最后ShowData类调用CreateXml的方法得到XML字符串,具体代码如下:

 

JavaBean:代表数据库表的一条记录的实体:

       

 import java.sql.Timestamp; import java.io.Serializable; /** * * * @author * @version 1.0 */ public class DataBean implements Serializable { /** * 缺省的构造函数 */ public DataBean() { } /** * invid */ private String invid = null; /** * invdate */ private String invdate = null; /** * client_id */ private String client_id = null; /** * amount */ private String amount = null; /** * tax */ private String tax = null; /** * total */ private String total = null; /** * note */ private String note = null; /** * 取得invid * * @return invid */ public String getInvid() { return this.invid; } /** * 设置invid * * @param 新的invid */ public void setInvid(String invid) { this.invid = invid; } /** * 取得invdate * * @return invdate */ public String getInvdate() { return this.invdate; } /** * 设置invdate * * @param 新的invdate */ public void setInvdate(String invdate) { this.invdate = invdate; } /** * 取得client_id * * @return client_id */ public String getClient_id() { return this.client_id; } /** * 设置client_id * * @param 新的client_id */ public void setClient_id(String client_id) { this.client_id = client_id; } /** * 取得amount * * @return amount */ public String getAmount() { return this.amount; } /** * 设置amount * * @param 新的amount */ public void setAmount(String amount) { this.amount = amount; } /** * 取得tax * * @return tax */ public String getTax() { return this.tax; } /** * 设置tax * * @param 新的tax */ public void setTax(String tax) { this.tax = tax; } /** * 取得total * * @return total */ public String getTotal() { return this.total; } /** * 设置total * * @param 新的total */ public void setTotal(String total) { this.total = total; } /** * 取得note * * @return note */ public String getNote() { return this.note; } /** * 设置note * * @param 新的note */ public void setNote(String note) { this.note = note; } /** * 调试用的方法, 可以将所有字段的数据输出 * */ public String toString() { StringBuffer sb = new StringBuffer("<row id='"); sb.append(invid); sb.append("'>"); sb.append("<cell>"); sb.append(invid); sb.append("</cell>"); sb.append("<cell>"); sb.append(DateUtil.getYyyy_MM_dd(DateUtil.createDateByString(invdate,"yyyy-mm-dd"))); sb.append("</cell>"); sb.append("<cell>"); sb.append(amount); sb.append("</cell>"); sb.append("<cell>"); sb.append(tax); sb.append("</cell>"); sb.append("<cell>"); sb.append(total); sb.append("</cell>"); sb.append("<cell><!--[CDATA["); sb.append(note); sb.append("]]--></cell>"); sb.append("</row>"); return sb.toString(); } }

 

CreatXml:用于生成xml字串的类:

 

import java.sql.SQLException; import java.util.ArrayList; public class CreateXml { public String createXml(String sqlStr,int intRecordsPerPage, int intCurrentPage) throws SQLException{ int count = DBUtil.getInstance().queryCount(sqlStr); String className = "util.DataBean"; int totalPage = 0; if (count > 0 ) { totalPage = (int)(Math.ceil((double)count/(double)intRecordsPerPage)); } else { totalPage = 0; } if (intCurrentPage > totalPage) { intCurrentPage = totalPage; } int begin = intRecordsPerPage*(intCurrentPage-1); if (begin < 0) { begin = 0; } ArrayList<DataBean> datas = (ArrayList<DataBean>)DBUtil.getInstance().queryData(sqlStr, className, begin, intRecordsPerPage); StringBuffer sb = new StringBuffer("<?xml version='1.0' encoding='utf-8'?>"); sb.append("<rows>"); sb.append("<page>"); sb.append(intCurrentPage); sb.append("</page>"); sb.append("<total>"); sb.append(totalPage); sb.append("</total>"); sb.append("<records>"); sb.append(count); sb.append("</records>"); for (DataBean data : datas) { sb.append(data.toString()); } sb.append("</rows>"); return sb.toString(); } }

 

servlet: ShowData类

 

public class ShowData extends HttpServlet { /** * Constructor of the object. */ public ShowData() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int page = 0; int rows = 0; String pPage = request.getParameter("page"); String pRows = request.getParameter("rows"); if (pPage!=null && !pPage.isEmpty()) { page = Integer.valueOf(pPage); } if (pRows!=null && !pRows.isEmpty()){ rows = Integer.valueOf(pRows); } String xml = null; try { xml = new CreateXml().createXml("invheader", rows, page); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(xml); response.setHeader("Content-type", "text/xml;charset=utf-8"); PrintWriter out = response.getWriter(); out.write(xml); out.flush(); out.close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }

 

DBUtil类这里就不贴出了,因为每个人都有可能有不同的实现,只要最后能取得数据返回xml形式的字符串就可以了。

在我的项目里配置的servlet访问路径如下servlet/ShowData,请注意这个跟上面的jsp里的jqGrid的属性配置里的

url:'servlet/ShowData'是一致的,显然url这个属性就是jqGrid用来指定数据读取路径的。

 

现在再此访问http://localhost:8080/TestJqtable

 

可以看到如下画面:

 

 

  

 

可以看到jqGrid将分页功能也做好了,其实不止如此,jqGrid还可以有编辑数据,添加数据,删除数据,查询数据,等强大功能。

 

  

 

你可能感兴趣的:(xml,String,servlet,null,insert,stylesheet)