Jqgrid安装(第一个Grid-xml)

前端之家收集整理的这篇文章主要介绍了Jqgrid安装(第一个Grid-xml)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
 

开始学习Jqgrid,记录学习的点点滴滴,大牛勿喷。

一、下载Jqgrid和UI theme:

Jqgrid下载地址:http://www.trirand.com/blog/?page_id=6 (说明:本文是基于Jqgrid3.6.5)

UI theme下载地址:http://jqueryui.com/download/ (说明:本文是基于Jquery UI -1.10.2)

二、安装:

步骤一:解压上述两个压缩包。

步骤二:在Web目录下创建一个文件夹用来放置jqgrid文件,例如:jqgrid。

步骤三:在jqgrid文件夹下,创建js文件夹和css文件夹。

步骤四:将jqgrid压缩包中的css文件夹下的ui.jqgrid.css文件复制到项目的css文件夹中;

将jqgrid压缩包中的js文件夹下所有文件复制到项目的js文件夹中。

步骤五:将jquery-ui-1.10.2压缩包中css文件夹下的ui-lightness文件夹复制到项目的css文件夹下。

此时目录为:

三、创建第一个Grid:

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<Meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
<title>my firstGrid</title>                                                                                                     <link rel="stylesheet" type="text/css" media="screen" href="jqgrid/css/ui-lightness/jquery-ui-1.10.2.custom.css" />   <!-- 加载用户UI主题 -->  
  <link rel="stylesheet" type="text/css" media="screen" href="jqgrid/css/ui.jqgrid.css" />                             <!-- 加载jqgrid样式 -->  
  <script src="jqgrid/js/jquery-1.4.2.min.js" type="text/javascript"></script>                                         <!-- 加载jquery -->  
  <script src="jqgrid/js/i18n/grid.locale-cn.js" type="text/javascript"></script>                                     <!-- 加载jqgrid语言文件 (必须在jqgrid文件之前加载)-->  
 <script src="jqgrid/js/jquery.jqGrid.min.js" type="text/javascript"></script>                                      <!-- 加载jqgrid文件 -->                                                                                                                       <!-- 统一字体和格式(推荐) -->  
<style>  
html,body {  
    margin: 0;  
    padding: 0;  
    font-size: 75%;  
}  
</style>  
  
  
  
<script type="text/javascript">  
        jQuery(document).ready(function(){   
              
          jQuery("#list").jqGrid({  
            url:'jqgrid_xml.do',datatype: 'xml',mtype: 'GET',colNames:['id','name','sex','mail','qq','tel','birthday'],colModel :[   
              {name:'id',index:'id',width:55},{name:'name',index:'name',width:90},{name:'sex',index:'sex',width:80,align:'right'},{name:'mail',index:'mail',{name:'qq',index:'qq',{name:'tel',index:'tel',{name:'birthday',index:'birthday',width:150,sortable:false}   
            ],pager: '#pager',rowNum:5,rowList:[5,10,20,30],sortname: 'id',sortorder: 'desc',viewrecords: true,caption: 'My first grid'  
          }).navGrid("#pager",{  
                edit : true,add : true,del : true,search : true,refresh : true  
            });   
        });   
</script>  
</head>  
  
  
<body>  
<table id="list"></table>   
<div id="pager"></div>  
</body>  
</html>  


四、创建表,根据以上colNames中的字段。(注意要在项目中加入jdbc包)

五、以xml的格式在grid中显示数据库中数据。

1、创建User实体类

package entity;

import java.util.Date;

public class User {
	private int id;
	private String name;
	private String sex;
	private String mail;
	private int qq;
	private int tel;
	private Date birthday;
	
	public int getTel() {
		return tel;
	}
	public void setTel(int tel) {
		this.tel = tel;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getMail() {
		return mail;
	}
	public void setMail(String mail) {
		this.mail = mail;
	}
	public int getQq() {
		return qq;
	}
	public void setQq(int qq) {
		this.qq = qq;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	
}

2、创建JqgridDao类操作数据库

package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.sqlException;
import java.util.ArrayList;
import java.util.List;

import entity.User;

public class JqgridDao {
	protected Connection conn = null;
	protected PreparedStatement pstmt = null;
	protected ResultSet res = null;
	private String driver = "oracle.jdbc.driver.OracleDriver";
	private String user = "system";
	private String password = "ok";
	private String url = "jdbc:oracle:thin:@localhost:1521:orcl";
	
	
	public void openCon(){
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url,user,password);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (sqlException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void closeCon(){
		try {
			if(res != null){
				res.close();
			}
			if(pstmt != null){
				pstmt.close();
			}
			if(conn != null){
				conn.close();
			}
		} catch (sqlException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 获取User表分页数据
	 * @return
	 */
	public List<User> getAll(int max,int min,String orderName,String order){
		List<User> list = new ArrayList<User>();
		this.openCon();
		//String sql = "select * from (select rownum rn,u.* from users u  order by ?,?) where rn>=? and rn<=?";
		String sql = "select * from (select rownum rn,u.* from (select * from users order by ?,?) u ) where rn>=? and rn<=?";
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,orderName);
			pstmt.setString(2,order);
			pstmt.setInt(3,min);
			pstmt.setInt(4,max);
			res = pstmt.executeQuery();
			
			while(res.next()){
				User user = new User();
				user.setId(res.getInt("id"));
				user.setMail(res.getString("mail"));
				user.setName(res.getString("name"));
				user.setQq(res.getInt("qq"));
				user.setTel(res.getInt("tel"));
				user.setSex(res.getString("sex"));
				user.setBirthday(res.getDate("birthday"));
				list.add(user);
			}
		} catch (sqlException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		this.closeCon();
		return list;
	}
	
	/**
	 * 获取User表总记录数
	 * @return
	 */
	public int getCount(){
		this.openCon();
		int count = 0 ;
		String sql = "select count(*) from users";
		try {
			pstmt = conn.prepareStatement(sql);
			res = pstmt.executeQuery();
			while(res.next()){
				count = res.getInt(1);
			}
		} catch (sqlException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.closeCon();
		return count;
	}
	
	
}


3、创建并配置一个Servlet:

package servlet;

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

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

import dao.JqgridDao;
import entity.User;

/**
 * Servlet implementation class JqgridServlet
 */
@WebServlet("/JqgridServlet")
public class JqgridServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public JqgridServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request,HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
		this.doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request,HttpServletResponse response)
	 * 获取数据库数据
	 */
	protected void doPost(HttpServletRequest request,IOException {
		response.setCharacterEncoding("utf-8");
		//获取jqgrid传过来的参数
		int page = Integer.parseInt(request.getParameter("page"));//得到请求的页数,默认为1
		int rows = Integer.parseInt(request.getParameter("rows"));//得到想要每页显示的行数
		String sidx = request.getParameter("sidx");//排序的列名
		String sord = request.getParameter("sord");//升序还是降序(asc or desc)
		//设置分页参数
		int min = (page-1) * rows + 1;
		int max = page * rows;
		JqgridDao jqDao = new JqgridDao();
		List list = jqDao.getAll(max,min,sidx,sord);
		
		//计算总页数
		int count = jqDao.getCount();
		int total = count % rows == 0 ? count/rows : count/rows + 1;
		
		//拼接xml
		StringBuffer result = new StringBuffer("<?xml version='1.0' encoding='utf-8'?>");
		result.append("<rows>");
		result.append("<page>"+page+"</page>");//当前页
		result.append("<total>"+total+"</total>");//总页数
		result.append("<records>"+count+"</records>");//总记录数
		for (int i = 0; i < list.size(); i++) {
			User user = (User) list.get(i);
			result.append("<row id='"+user.getId()+"'>");
			result.append("<cell>"+user.getId()+"</cell>");
			result.append("<cell>"+user.getName()+"</cell>");
			result.append("<cell>"+user.getSex()+"</cell>");
			result.append("<cell>"+user.getMail()+"</cell>");
			result.append("<cell>"+user.getQq()+"</cell>");
			result.append("<cell>"+user.getTel()+"</cell>");
			result.append("<cell>"+user.getBirthday()+"</cell>");
			result.append("</row>");
		}
		result.append("</rows>");
		
		PrintWriter out = response.getWriter();
		out.print(result.toString());
		
	}

}


在web.xml中配置

<servlet>
  	<servlet-name>jqgridServlet</servlet-name>
  	<servlet-class>servlet.JqgridServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>jqgridServlet</servlet-name>
  	<url-pattern>/jqgrid_xml.do</url-pattern>
  </servlet-mapping>

六、第二种xml配置(拼接xml的方式不同):

1、jsp:


<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<Meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>my firstGrid</title>


<!--------------------------- 普通版本的配置------------------------------------>
  <link rel="stylesheet" type="text/css" media="screen" href="jqgrid/css/ui-lightness/jquery-ui-1.10.2.custom.css" />   <!-- 加载用户UI主题 -->
  <link rel="stylesheet" type="text/css" media="screen" href="jqgrid/css/ui.jqgrid.css" />                             <!-- 加载jqgrid样式 -->
  <script src="jqgrid/js/jquery-1.4.2.min.js" type="text/javascript"></script>                                         <!-- 加载jquery -->
  <script src="jqgrid/js/i18n/grid.locale-cn.js" type="text/javascript"></script>                                     <!-- 加载jqgrid语言文件 (必须在jqgrid文件之前加载)-->
 <script src="jqgrid/js/jquery.jqGrid.min.js" type="text/javascript"></script>                                      <!-- 加载jqgrid文件 -->
 
<!-- 统一字体和格式(推荐) -->
<style>
html,body {
    margin: 0;
    padding: 0;
    font-size: 75%;
}
</style>


<script type="text/javascript">
// 设置全局属性(隔行换色)
jQuery.extend(jQuery.jgrid.defaults,{ altRows:true });
</script>

<script type="text/javascript">
		jQuery(document).ready(function(){ 
		  jQuery("#list").jqGrid({
		    url:'jqgrid_xml2.do',//返回数据的类型
		    mtype: 'GET',//get or post
		    colNames:['id',colModel :[ 
		      {
		      	name:'id',//name不一定要和表名相同
		      	index:'id',//?
		      	xmlmap : 'id',//设置得到数据的字段名称(注:Jqgrid先识别'xmlmap',如果未设置xmlmap,则识别name;前提是xmlReader中的repeatitems设置为'false')
		      	width:55,align:'center',//align:对齐方式
		      	sortable:false   //sortable:点击该列是否能排序
		      },width:90,align:'center'},},sortable:false,align:'center'} 
		    ],altRows:false,//取消斑马纹(隔行换色),注:覆盖了全局设置
		    pager: '#pager',//设置导航栏
		    rowNum:5,//每页显示的行数
		    rowList:[5,//每页显示的行数(可在前台更改)
		    sortname: 'id',//排序的列名(初始时)
		    sortorder: 'desc',//排序的方式
		    viewrecords: true,//是否可以看到总记录
		    caption: 'My first grid',//设置标题栏,不设标题栏将不可见
		    xmlReader : {
		    	root : 'rows',//根节点
		    	row : 'row',//行节点(必须是根节点的子节点)
		    	page : 'page',//当前页
		    	total : 'total',//总页数
		    	records : 'records',//总记录数
		    	repeatitems : false,//!此时应设为false,并且没有cell属性
		    	id : '[id]'//?
		    	//id : '[id]',行中的id属性值
		    }
		    
		  }).navGrid("#pager",{
				edit : true,refresh : true
			}); 
		}); 
</script>
</head>


<body>
<table id="list"></table> 
<div id="pager"></div>
</body>
</html>


2、Servlet:

package servlet;

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

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

import dao.JqgridDao;
import entity.User;

/**
 * Servlet implementation class JqgridServlet
 */
@WebServlet("/JqgridServlet")
public class Servlet4Xml2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Servlet4Xml2() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request,sord);
		
		//计算总页数
		int count = jqDao.getCount();
		int total = count % rows == 0 ? count/rows : count/rows + 1;
		
		//拼接xml
		StringBuffer result = new StringBuffer("<?xml version='1.0' encoding='utf-8'?>");
		result.append("<rows>");
		result.append("<page>"+page+"</page>");//当前页
		result.append("<total>"+total+"</total>");//总页数
		result.append("<records>"+count+"</records>");//总记录数
		
		//拼接的格式与Grid4Xml1不同(cell换成字段名称作为标签名称)
		for (int i = 0; i < list.size(); i++) {
			User user = (User) list.get(i);
			result.append("<row id='"+user.getId()+"'>");
			result.append("<id>"+user.getId()+"</id>");
			result.append("<name>"+user.getName()+"</name>");
			result.append("<sex>"+user.getSex()+"</sex>");
			result.append("<mail>"+user.getMail()+"</mail>");
			result.append("<qq>"+user.getQq()+"</qq>");
			result.append("<tel>"+user.getTel()+"</tel>");
			result.append("<birthday>"+user.getBirthday()+"</birthday>");
			result.append("</row>");
		}
		result.append("</rows>");
		
		PrintWriter out = response.getWriter();
		out.print(result.toString());
		
	}

}

其他不做改变。

猜你在找的XML相关文章