程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java中jqGrid 進修筆記整頓——進階篇(二)

Java中jqGrid 進修筆記整頓——進階篇(二)

編輯:關於JAVA

Java中jqGrid 進修筆記整頓——進階篇(二)。本站提示廣大學習愛好者:(Java中jqGrid 進修筆記整頓——進階篇(二))文章只能為提供參考,不一定能成為您想要的結果。以下是Java中jqGrid 進修筆記整頓——進階篇(二)正文


相干浏覽:

Java中jqGrid 進修筆記整頓——進階篇(一)

本篇開端正式與後台(java說話)停止數據交互,應用的平台為

JDK:java 1.8.0_71

myEclisp 2015 Stable 2.0

Apache Tomcat-8.0.30

Mysql 5.7

Navicat for mysql 11.2.5(mysql數據庫治理對象)

1、數據庫部門

1、創立數據庫

應用Navicat for mysql創立數據庫(應用其他對象或直接應用敕令行暫不引見)

2、

2.創立表

雙擊翻開上步創立數據庫——右擊Tables——選擇New Table

樹立以下字段 保留時會提醒輸出表名

2、法式部門

1、新建項目

應用myEclipse新建——Web Project

輸出項目稱號 選擇java和運轉該項目標Tomcat 一向點下一步 直到下圖頁面 點選上面主動生成web.xml文件的復選框 後完成


創立以下包構造並新建一個vo類(屬性與數據庫字段逐個對應)

demo.java

package com.xeonmic.vo;
public class demo {
private int id;
private String name;
private int type;
private double pay;
private String text;
public demo() {
// TODO Auto-generated constructor stub
}
public demo(int id, int type, Double pay,String name, String text) {
this.id = id;
this.name = name;
this.type = type;
this.pay = pay;
this.text = text;
}
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 int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public double getPay() {
return pay;
}
public void setPay(Double pay) {
this.pay = pay;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public String toString() {
return "demo [id=" + id + ", name=" + name + ", type=" + type
+ ", pay=" + pay + ", text=" + text + "]";
}
}

2、導入數據庫銜接和JSON文件的jar包

數據庫銜接jar包可以在mysql裝置目次的以下目次查找到

別的下載JSON所需jar包,已上傳百度雲(http://pan.百度.com/s/1dETGjRV)一路復制粘貼到WebRoot/WEB-INF/lib目次下

然後全選右鍵添加到構建途徑

3、DAO設計形式的根本分層完成

參考《Java Web開辟實戰經典基本篇》這裡不在論述直接貼源碼後續零丁開一篇專門講這部門基本常識

—3.1、DatabaseConnection.java

package com.xeonmic.dbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
private static final String DBDRIVER="org.gjt.mm.mysql.Driver";
private static final String DBURL="jdbc:mysql://localhost:3306/jqgriddemo";
private static final String DBUSER="root";
private static final String DBPASSWORD="1234";
private Connection conn =null;
public DatabaseConnection(){
try {
Class.forName(DBDRIVER);
this.conn = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD);
} catch (ClassNotFoundException e) {
// TODO 主動生成的 catch 塊
e.printStackTrace();
} catch (SQLException e) {
// TODO 主動生成的 catch 塊
e.printStackTrace();
}
//System.out.println("銜接數據庫勝利");
}
public Connection getConnection(){
return this.conn;
}
public void close(){
if(this.conn != null){
try {
this.conn.close();
} catch (SQLException e) {
// TODO 主動生成的 catch 塊
e.printStackTrace();
}
}
}
}

—3.2、DemoDAO.java

package com.xeonmic.dao;
import java.util.List;
import com.xeonmic.vo.demo;
public interface DemoDAO {
//添加辦法
public boolean doCreate(demo demo);
//查詢辦法
public List<demo> doSearch(String keys);
//刪除辦法
public boolean doDelete(int id);
//修正辦法
public boolean doChange(demo demo);
}

—3.3、DemoDAOImpl.java

package com.xeonmic.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.xeonmic.dao.DemoDAO;
import com.xeonmic.vo.demo;
public class DemoDAOImpl implements DemoDAO {
private Connection conn = null;
private PreparedStatement pstmt = null;
public DemoDAOImpl(Connection conn){
this.conn=conn;
}
@Override
public boolean doCreate(demo demo) {
boolean flag = false;
String sql = "INSERT INTO t_demo(type,pay,name,text ) VALUES(?,?,?,?)";
try {
this.pstmt = this.conn.prepareStatement(sql);
this.pstmt.setInt(1, demo.getType());
this.pstmt.setDouble(2, demo.getPay());
this.pstmt.setString(3, demo.getName());
this.pstmt.setString(4, demo.getText());
if(this.pstmt.executeUpdate()>0){
flag = true;
}
this.pstmt.close();
} catch (SQLException e) {
// TODO 主動生成的 catch 塊
e.printStackTrace();
}
return flag;
}
@Override
public List<demo> doSearch(String keys) {
// TODO Auto-generated method stub
if (keys==null) {
keys="";
}
String sql = "SELECT id,name,type,pay,text FROM t_demo "+keys;
List<demo> all = new ArrayList<demo>();
System.out.println(sql);
try { 
this.pstmt = this.conn.prepareStatement(sql); 
ResultSet rs = this.pstmt.executeQuery();
demo demo = null;
while(rs.next()){
demo = new demo(rs.getInt("id"),rs.getInt("type"),rs.getDouble("pay"),rs.getString("name"),rs.getString("text")); 
all.add(demo);
}
this.pstmt.close(); 
} catch (SQLException e) {
// TODO 主動生成的 catch 塊
e.printStackTrace();
}
return all;
}
@Override
public boolean doDelete(int id) {
boolean flag = false;
String sql = "DELETE FROM t_demo WHERE id = ?";
try {
this.pstmt = this.conn.prepareStatement(sql);
this.pstmt.setInt(1, id);
if(this.pstmt.executeUpdate()>0){
flag = true;
}
this.pstmt.close();
} catch (SQLException e) {
// TODO 主動生成的 catch 塊
e.printStackTrace();
}
return flag;
}
@Override
public boolean doChange(demo demo) {
boolean flag = false;
String sql = "UPDATE t_demo SET type=?,pay=?,name=?,text=? WHERE id=?";
try {
this.pstmt = this.conn.prepareStatement(sql);
this.pstmt.setInt(5, demo.getId());
this.pstmt.setInt(1, demo.getType());
this.pstmt.setDouble(2, demo.getPay());
this.pstmt.setString(3, demo.getName());
this.pstmt.setString(4, demo.getText());
if(this.pstmt.executeUpdate()>0){
flag = true;
}
this.pstmt.close();
} catch (SQLException e) {
// TODO 主動生成的 catch 塊
e.printStackTrace();
}
return flag;
}
}

—3.5、Factory.java

package com.xeonmic.factory;
import com.xeonmic.dao.DemoDAO;
import com.xeonmic.dao.proxy.DemoDAOProxy;
public class Factory {
public static DemoDAO getDemoDAOInstance(){
return new DemoDAOProxy();
}
}

—3.6、Demotest.java(對後面的辦法停止一次簡略測試)

package com.xeonmic.test;
import java.util.LinkedList;
import java.util.List;
import com.xeonmic.factory.Factory;
import com.xeonmic.vo.demo;
public class Demotest {
public static void main(String[] args) {
demo demo1 = new demo();
demo1.setName("Name");
demo1.setPay(0.98);
demo1.setType(1);
demo1.setText("Text");
doCreate(demo1);
doSearch(null);
if (doSearch(null)!=null&&!doSearch(null).isEmpty()) {
demo1 = doSearch("").get(0);
demo1.setText("Change Text");
doChange(demo1);
doSearch("WHERE id = "+demo1.getId());
doDelete(demo1.getId());
doSearch(null);
}
}
public static List<demo> doSearch(String keys) {
List<demo> allDemos = new LinkedList<demo>();
allDemos = Factory.getDemoDAOInstance().doSearch(keys);
for (demo demo : allDemos) {
System.out.println(demo.toString());
}
return allDemos;
}
public static void doCreate(demo demo) {
if (Factory.getDemoDAOInstance().doCreate(demo)) {
System.out.println("添加勝利");
}else {
System.out.println("添加掉敗");
}
}
public static void doChange(demo demo) {
if (Factory.getDemoDAOInstance().doChange(demo)) {
System.out.println("修正勝利");
}else {
System.out.println("修正掉敗");
}
}
public static void doDelete(int id) {
if (Factory.getDemoDAOInstance().doDelete(id)) {
System.out.println("刪除勝利");
}else {
System.out.println("刪除掉敗");
}
}
}
/*
* 輸入成果
添加勝利
SELECT id,name,type,pay,text FROM t_demo 
demo [id=1, name=Name, type=1, pay=0.98, text=Text]
SELECT id,name,type,pay,text FROM t_demo 
demo [id=1, name=Name, type=1, pay=0.98, text=Text]
SELECT id,name,type,pay,text FROM t_demo 
demo [id=1, name=Name, type=1, pay=0.98, text=Text]
SELECT id,name,type,pay,text FROM t_demo 
demo [id=1, name=Name, type=1, pay=0.98, text=Text]
修正勝利
SELECT id,name,type,pay,text FROM t_demo WHERE id = 1
demo [id=1, name=Name, type=1, pay=0.98, text=Change Text]
刪除勝利
SELECT id,name,type,pay,text FROM t_demo 
* */

4、JSP頁面和Servlet部門(主要)

—4.1、index.jsp(將index.html中html標簽到html標簽中的內容調換index.jsp中html的內容並對JS停止以下修正)

<%@ 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>
<title>DEMO</title>
<link rel="stylesheet" type="text/css" href="css/jquery-ui.min.css" />
<link rel="stylesheet" type="text/css" href="css/jquery-ui.theme.min.css" />
<link rel="stylesheet" type="text/css" href="css/ui.jqgrid-bootstrap-ui.css" />
<link rel="stylesheet" type="text/css" href="css/ui.jqgrid.css" />
</head>
<body>
<div class="main" id="main">
<!--jqGrid地點-->
<table id="grid-table"></table>
<!--jqGrid 閱讀導航欄地點-->
<div id="grid-pager"></div>
</div>
<script src="js/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/i18n/grid.locale-cn.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
//當 datatype 為"local" 時需填寫 
var grid_selector = "#grid-table";
var pager_selector = "#grid-pager";
$(document).ready(function() {
$("#grid-table").jqGrid({
//用於檢索的Servlet URL
url:"<%=basePath%>"+"demoServlet", 
//用於添加、修正、刪除的Servlet URL
editurl: "<%=basePath%>"+"demochangeServlet",
//data: grid_data, //當 datatype 為"local" 時需填寫 
datatype:"json", //數據起源,當地數據(local,json,jsonp,xml等)
height: 150, //高度,表格高度。可為數值、百分比或'auto'
mtype:"GET",//提交方法
colNames: ['出庫單號', '出庫類型', '總金額', '請求人(單元)', '備注'],
colModel: [{
name: 'id',
index: 'id', //索引。其和後台交互的參數為sidx
key: true, //當從辦事器端前往的數據中沒有id時,將此作為獨一rowid應用只要一個列可以做這項設置。假如設置多於一個,那末只拔取第一個,其他被疏忽
width: 100,
editable: false,
editoptions: {
size: "20",
maxlength: "30"
}
}, {
name: 'type',
index: 'type',
width: 200, //寬度
editable: true, //能否可編纂
edittype: "select", //可以編纂的類型。可選值:text, textarea, select, checkbox, password, button, image and file.s
editoptions: {
value: "1:推銷入庫;2:退用入庫"
}
}, {
name: 'pay',
index: 'pay',
width: 60,
sorttype: "double",
editable: true
}, {
name: 'name',
index: 'name',
width: 150,
editable: true,
editoptions: {
size: "20",
maxlength: "30"
}
}, {
name: 'text',
index: 'text',
width: 250,
sortable: false,
editable: true,
edittype: "textarea",
editoptions: {
rows: "2",
cols: "10"
}
}, ],
viewrecords: true, //能否在閱讀導航欄顯示記載總數
rowNum: 10, //每頁顯示記載數
rowList: [10, 20, 30], //用於轉變顯示行數的下拉列表框的元素數組。
pager: pager_selector, //分頁、按鈕地點的閱讀導航欄
altRows: true, //設置為瓜代行表格,默許為false
//toppager: true,//能否在下面顯示閱讀導航欄
multiselect: true, //能否多選
//multikey: "ctrlKey",//能否只能用Ctrl按鍵多選
multiboxonly: true, //能否只能點擊復選框多選
// subGrid : true, 
//sortname:'id',//默許的排序列名
//sortorder:'asc',//默許的排序方法(asc升序,desc降序)
caption: "推銷退貨單列表", //表名
autowidth: true //主動寬
});
//閱讀導航欄添加功效部門代碼
$(grid_selector).navGrid(pager_selector, {
search: true, // 檢索
add: true, //添加 (只要editable為true時能力顯示屬性)
edit: true, //修正(只要editable為true時能力顯示屬性)
del: true, //刪除
refresh: true //刷新
}, {}, // edit options
{}, // add options
{}, // delete options
{
multipleSearch: true
} // search options - define multiple search
);
});
</script>
</body>
</html>

—4.2、demoServlet.java

package com.xeonmic.action;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.xeonmic.factory.Factory;
import com.xeonmic.vo.demo;
/**
* Servlet implementation class demoServlet
*/
public class demoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8"); //這裡不設置編碼會有亂碼
response.setContentType("text/html;charset=utf-8");
response.setHeader("Cache-Control", "no-cache"); 
int rows = Integer.valueOf(request.getParameter("rows")); //每頁中顯示的記載行數
int page = Integer.valueOf(request.getParameter("page")); //以後的頁碼
String sord = request.getParameter("sord");//排序方法
String sidx = request.getParameter("sidx");//排序列名
Boolean search =(request.getParameter("_search").equals("true"))?true:false;//能否用於查詢要求
List<demo> allList = new LinkedList<demo>();//前往成果集
String keys="";//查詢前提字符串
if(search){
keys=" WHERE ";
String filters = request.getParameter("filters");//詳細的前提
System.out.println(filters);
//傳入數據的格局是相似如許的:"{"groupOp":"AND","rules":[{"field":"id","op":"eq","data":"1"},{"field":"type","op":"ew","data":"2"}]}"
JSONObject jsonObject = JSONObject.fromObject(filters);
String groupOp = "AND";//每一個規矩之間的關系(and/or)
if (jsonObject.getString("groupOp")!=null&&!"".equals(jsonObject.getString("groupOp"))) {
if (jsonObject.getString("groupOp").equals("OR")) {
groupOp = "OR";
}
}
JSONArray rulesjson = jsonObject.getJSONArray("rules");
//遍歷每一個前提
for (int z=0; z < rulesjson.size(); z++) {
Object t = rulesjson.get(z);
JSONObject rulejson = JSONObject.fromObject(t);
String field = rulejson.getString("field");
String op = rulejson.getString("op");
String data = rulejson.getString("data");
String string = "";//用於存儲單個前提sql語句片斷
//開端轉化為sql語句
switch (op) {
case "eq"://相等
string=" = '"+data+"' ";
break;
case "ne"://不相等
string=" <> '"+data+"' ";
break;
case "li"://小於
string=" < '"+data+"' ";
break;
case"le"://小於等於
string=" <= '"+data+"' ";
break;
case"gt"://年夜於
string=" > '"+data+"' ";
break;
case "ge"://年夜於等於
string=" >= '"+data+"' ";
break;
case "bw"://在...之間
{
if (data.split(",").length==2) {
string=" BETWEEN '"+data.split(",")[0]+"' AND '"+data.split(",")[1]+"' ";
}else {
string=" = '"+data+"' ";//數據毛病時處置
}
} 
break;
case"bn"://不在...之間
{
if (data.split(",").length==2) {
string=" NOT BETWEEN '"+data.split(",")[0]+"' AND '"+data.split(",")[1]+"' ";
}else {
string=" <> '"+data+"' ";//數據毛病時處置
}
}
break;
case"ew"://以...停止
string=" LIKE '%"+data+"' ";
break;
case "en"://不以...停止
string=" NOT LIKE '%"+data+"' ";
break;
case "cn"://包括
string=" LIKE '%"+data+"%' ";
break;
case "nc"://不包括
string=" NOT LIKE '%"+data+"%' ";
break;
case "in"://在
{
string=" IN ( ";
String[] datas = data.split(",");
for (int i = 0; i < datas.length; i++) {
string+= " '"+datas[i]+"' ";
if (i!=datas.length-1) {
string += ",";
}else {
string += " ) ";
}
}
}
break;
case "ni"://不在
{
string=" NOT IN ( ";
String[] datas = data.split(",");
for (int i = 0; i < datas.length; i++) {
string+= " '"+datas[i]+"' ";
if (i!=datas.length-1) {
string += ",";
}else {
string += " ) ";
}
}
}
break;
default:
op=null;
System.out.println("OP符號毛病");//OP符號毛病
}
if (op!=null) {
if (z==rulesjson.size()-1) {
keys+=" "+field+" "+string +" ";
}else {
keys+=" "+field+" "+string +" "+groupOp+" ";
}
}
}
}
//起落序SQL語句轉換
if (sidx!=null&&!"".equals(sidx)) {
System.out.println(sidx);
keys += " ORDER BY " + sidx;
System.out.println("sord="+sord);
if (!sord.equals("asc")) {
keys += " DESC ";
}
}
allList = Factory.getDemoDAOInstance().doSearch(keys);
//分頁部門
int total=0; 
total=(allList.size()%rows==0)?(allList.size()/rows):((allList.size()/rows)+1);
int j = 0;
int m = (page-1)*rows;
int n = (page-1)*rows+rows;
JSONArray jArray = new JSONArray();
for (j=m; j<allList.size()&&j<n; j++) { 
jArray.add(JSONObject.fromObject(allList.get(j))); 
}
JSONObject jjson = new JSONObject(); 
//檢索成果及分頁信息封裝 前往
jjson.accumulate("page", page);
jjson.accumulate("total", total);
jjson.accumulate("records", allList.size());
jjson.accumulate("rows", jArray);
System.out.println(jjson.toString());
response.getWriter().write(jjson.toString());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doGet(request, response);
}
}

—4.3、demochangeServlet.java

package com.xeonmic.action;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xeonmic.factory.Factory;
import com.xeonmic.vo.demo;
public class demochangeServlet extends HttpServlet {
/**
* 
*/
private static final long serialVersionUID = 1L;
/**
* 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 {
boolean flag = false;
String oper =request.getParameter("oper");
switch (oper) {
case "del":
{
String[] ids = request.getParameter("id").split(",");
for (int i = 0; i < ids.length; i++) {
int id =Integer.valueOf(ids[i]);
flag=Factory.getDemoDAOInstance().doDelete(id);
}
} 
break;
case "add":
{
int type = Integer.valueOf(request.getParameter("type"));
Double pay = Double.valueOf(request.getParameter("pay"));
String name = request.getParameter("name");
String text = request.getParameter("text");
demo demo = new demo(-1,type,pay,name,text);
flag = Factory.getDemoDAOInstance().doCreate(demo); 
}
break;
case "edit":
{
int id = Integer.valueOf(request.getParameter("id"));
int type = Integer.valueOf(request.getParameter("type"));
Double pay = Double.valueOf(request.getParameter("pay"));
String name = request.getParameter("name");
String text = request.getParameter("text");
demo demo = new demo(id,type,pay,name,text);
flag = Factory.getDemoDAOInstance().doChange(demo); 
}
break;
default:
break;
}
System.out.println(flag);
}
/**
* 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 {
this.doGet(request, response);
}
}

—4.4、web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>jqGrid</display-name>
<servlet>
<servlet-name>demoServlet</servlet-name>
<servlet-class>com.xeonmic.action.demoServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>demochangeServlet</servlet-name>
<servlet-class>com.xeonmic.action.demochangeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demoServlet</servlet-name>
<url-pattern>/demoServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>demochangeServlet</servlet-name>
<url-pattern>/demochangeServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

至此,jqGrid單表功效已全體完成,例子中有哪些設計有成績請告訴,下一篇將開端處理 主從表 的設計完成,敬請存眷劇本直接網站!

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved