1. 程式人生 > >使用Struts2和jQuery EasyUI實現簡單CRUD系統(五)——jsp,json,EasyUI的結合

使用Struts2和jQuery EasyUI實現簡單CRUD系統(五)——jsp,json,EasyUI的結合

元素 word cli resultset sheet 傳輸 charset {} tco

這部分比較復雜,之前看過自己的同學開發一個選課系統的時候用到了JSON,可是一直不知道有什麽用。寫東西也沒用到。所以沒去學他。然後如今以這樣的懷著好奇心,這是做什麽用的,這是怎麽用的。這是怎麽結合的心態去學習,效果非常好。


這次用到的EasyUI的數據網格,DataGrid。

需用引用一個url傳來的json數據。然後整齊美觀地展如今頁面上。想想自己之前做的東西。就直接拿數據庫的數據和html的table代碼進行拼接,整潔是整潔,可是代碼寫得特別別扭。

讓我站在一個設計者的思路上來看,假設我如今提供了一個表格模板。然後我要將你的數據讀取進去之後再進行順序的排列,那麽我們就須要定義一種通用的格式了,我能讀取不論什麽遵循這樣的格式的數據並把它展如今DataGird中。這就是EasyUI的功能,而格式的功能是誰實現呢——JSON登場了。


JSON,javascript object notation,js對象標記(表示)法,相似xml可是比xml小且快。xml提取元素的話使用dom操作,須要child這些東西。


JSON能通過js解析和ajax傳輸。對了,要的就是這個。


談到ajax順便也再看了一下,曾經用的都忘記了。ajax做到的功能就是頁面的不刷新而偷偷與server連接後拿到數據再返回到前端。



我這個表格展如今這裏。事實上我要的數據是偷偷用了ajax拿到數據。而且通過js解析之後再準確地放回表格中。


(一)JSON

語法規則:

分名稱和值對,數據分隔 : {}保存對象 []保存數組“a”:1 相應js中的 a = 1。

json數據樣例:
[{"id":1,"name":"ee","password":"1"},
{"id":2,"name":"df2","password":"123"},
{"id":3,"name":"45ty","password":"123"},
{"id":4,"name":"sdfy","password":"123"},
{"id":10,"name":"sdfy","password":"123"}]


註意:有些人數據沒正常顯示出來還給我了踩。

今天發現了問題。

由於在後臺處理是。有些人為了避免使用轉義字符。直接將雙引號改為單引號。
String json = "[{‘id‘:1,‘name‘:‘ee‘,‘password‘:‘1‘}]";

這樣datagrid根本就載入不到數據。改為轉義字符正常
String json = "[{\"id\":1,\"name\":\"ee\",\"password\":\"1\"}]";

數組裏有4個元素,一個元素是一個對象:有id,name和password。


(二)EasyUI的DataGrid獲取json數據。

DataGrid:

<%@ 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>
<script src="http://localhost:8080/EasyProject/jquery.min.js" type="text/javascript"></script>
<script src="http://localhost:8080/EasyProject/jquery.easyui.min.js" type="text/javascript"></script>
<link href="http://localhost:8080/EasyProject/themes/default/easyui.css" rel="stylesheet"type="text/css" />
<link href="http://localhost:8080/EasyProject/themes/icon.css" rel="stylesheet" type="text/css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<table id="dg" title="My Users" class="easyui-datagrid" style="width:550px;height:250px"
		url="list_ej"
		toolbar="#toolbar"
		rownumbers="true" fitColumns="true" singleSelect="true">
	<thead>
		<tr>
<!-- 			<th field="id" width="50">id</th>
			<th field="name" width="50">name</th>
			<th field="password" width="50">password</th> -->
			
<!-- 		這樣的寫法也是能夠的	    <th data-options="field:‘id‘,width:150">id</th> -->

                <th field="id",width=“120">id</th>
                <th field="name",width="120">name</th>
                <th data-options="field:‘password‘,width:‘120‘,align:‘right‘">password</th>
		</tr>
	</thead>
</table>
<div id="toolbar">
	<a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">新建</a>
	<a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">改動</a>
	<a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="destroyUser()">刪除</a>
</div>

</body>
</html>

url="list_ej"

重點的地方就是url,url寫的一定要是返回json格式數據的url,我們用了action就能夠通過這個url跳到響應的jsp頁面。

list_ej通過以下的action拿到數據之後。再跳到list_ej.jsp。


action裏面拿到數據庫數據並進行json數據的轉換,網上一查的所有都是復制黏貼用了json框架的。有代碼的那些又寫得亂起八糟。自己摸索了好久。

JSONArray能夠將list裏面的數據轉換成JSON格式。

public String list_ej(){
		ActionContext ctx=ActionContext.getContext();
		Connection c = ConnectToSQL.getConn();
		Statement st = ConnectToSQL.getSt(c);
		List<User> list = new ArrayList<User>();
		String result="{}";
		try {
			ResultSet rs = st.executeQuery("select * from user");
			while(rs.next()){
				User u = new User();
				u.setId(rs.getInt("userid"));
				u.setName(rs.getString("username"));
				u.setPassword(rs.getString("password"));
				list.add(u);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		List<User> o  = JSONArray.fromObject(list);
		result=o.toString();
		try {
//			ServletActionContext.getResponse().getWriter().println(JSONArray.fromObject(list));
			ctx.put("json", result);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return "success";
	}

我們拿到數據之後,使用原生的JSON類,進行JSON格式的轉換,然後再把字符串返回到另外一個頁面List_ej.jsp。這個頁面就是終於DataGrid取數據的地方。


問題所在

這裏自己挖了一個大坑:自己之前寫的jsp。

<[email protected] import="com.opensymphony.xwork2.ActionContext"%>
<%@ 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">
<%@ page import="util.*, org.apache.struts2.ServletActionContext"%>
    <%@ taglib prefix="s" uri="/struts-tags"%>  
<%@ page import="java.sql.*,java.util.*,net.sf.json.*"%>
<%!
	Connection c = null;
	Statement st = null;
	ResultSet rs = null;
	String s = "";
%>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



<html>
<head>
<script src="http://localhost:8080/EasyProject/jquery.min.js" type="text/javascript"></script>
<script src="http://localhost:8080/EasyProject/jquery.easyui.min.js" type="text/javascript"></script>
<link href="http://localhost:8080/EasyProject/themes/default/easyui.css" rel="stylesheet"type="text/css" />
<link href="http://localhost:8080/EasyProject/themes/icon.css" rel="stylesheet" type="text/css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<table id="dg" title="My Users" class="easyui-datagrid" style="width:550px;height:250px"
		toolbar="#toolbar"
		rownumbers="true" fitColumns="true" singleSelect="true">
	<thead>
		<tr>
			<th field="id" width="50">id</th>
			<th field="name" width="50">name</th>
			<th field="password" width="50">password</th>
		</tr>
	</thead>
</table>
<div id="toolbar">
	<a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">New User</a>
	<a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">Edit User</a>
	<a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="destroyUser()">Remove User</a>
</div>
<%
/* Connection c = ConnectToSQL.getConn();
Statement st = ConnectToSQL.getSt(c);
List<User> list = new ArrayList<User>();
try {
	ResultSet rs = st.executeQuery("select * from user");
	while(rs.next()){
		User u = new User();
		u.setId(rs.getInt("userid"));
		u.setName(rs.getString("username"));
		u.setPassword(rs.getString("password"));
		list.add(u);
	}
} catch (SQLException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}
List<User> o  = JSONArray.fromObject(list); */
String json=(String)request.getAttribute("json");
System.out.println(json);
%>

<%=json%>
</body>
</html>

這樣的邏輯是沒有問題的,就是一直顯示不出來。調了好久。

事實上問題在於————我寫太多東西了。

list_jsp裏面僅僅須要:

<%
String json=(String)request.getAttribute("json");
%>
<%=json%>

最後,DataGird順利取到數據庫數據。

技術分享


使用Struts2和jQuery EasyUI實現簡單CRUD系統(五)——jsp,json,EasyUI的結合