新建個(gè)user.js 里面放入一下內(nèi)容:
Ext.onReady(function() {
var record_start = 0;
var num = function(v,p,Record,rowIndex){
return record_start + rowIndex + 1;
};
function renderSex(value) {
if (value == '1') {
return "<span style='color:blue'>先生</span>";
} else {
return "<span style='color:orange'>女士</span>";
}
}
var comboSex = [
['0','女'],
['1','男']
];
var sm = new Ext.grid.CheckboxSelectionModel({
handleMouseDown : Ext.emptyFn
}); // 創(chuàng)建復(fù)選框
var cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({
renderer : num
}), // 創(chuàng)建自動(dòng)行號(hào)
sm, {
header : '姓名',
dataIndex : 'stuName',
editor : new Ext.grid.GridEditor(new Ext.form.TextField({
allowBlank : false
})),
sortable : true
}, {
header : '性別',
dataIndex : 'stuSex',
editor : new Ext.grid.GridEditor(new Ext.form.ComboBox({
store : new Ext.data.SimpleStore({
fields : ['value', 'text'],
data : comboSex
}),
emptyText : '請(qǐng)選擇',
mode : 'local',
triggerAction : 'all',
valueField : 'value',
displayField : 'text',
readOnly : true
})),
renderer : renderSex,
sortable : true
}, {
header : '年齡',
dataIndex : 'stuAge',
editor : new Ext.grid.GridEditor(new Ext.form.NumberField({
allowBlank : false
})),
sortable : true
}, {
header : '住址',
dataIndex : 'stuAddr',
editor : new Ext.grid.GridEditor(new Ext.form.TextField({
allowBlank : false
})),
sortable : true
}, {
header : '電話',
dataIndex : 'stuTel',
editor : new Ext.grid.GridEditor(new Ext.form.NumberField({
allowBlank : false
})),
sortable : true
}]);
// 定義類型
var Record = Ext.data.Record.create([{
name : 'stuId',
type : 'int'
}, {
name : 'clsId',
type : 'int'
}, {
name : 'stuSex',
type : 'int'
}, {
name : 'stuName',
type : 'string'
}, {
name : 'stuAge',
type : 'int'
},{
name : 'stuAddr',
type : 'string'
},{
name : 'stuTel',
type : 'String'
}]);
var store = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : 'servlet/Query'
}),
pruneModifiedRecords: true,
reader : new Ext.data.JsonReader({
totalProperty : 'totalProperty',
root : 'root'
}, [{
name : 'stuId'
}, {
name : 'clsId'
}, {
name : 'stuSex'
}, {
name : 'stuName'
}, {
name : 'stuAge'
}, {
name : 'stuAddr'
}, {
name : 'stuTel'
}])
});
// var grid = new Ext.grid.GridPanel({ // 不可編輯的grid
var grid = new Ext.grid.EditorGridPanel({ // 可編輯的grid
title : '學(xué)生信息管理',
autoHeight : true,
cm : cm,
sm : sm,
renderTo : 'grid',
store : store,
// 分頁(yè)底端顯示工具條
bbar : new Ext.PagingToolbar({
pageSize : 10,
displayInfo : true,
store : store,
displayMsg : '顯示第{0}條到{1}條記錄,一共{2}條',
emptyMsg : '沒(méi)有記錄',
doLoad: function(start){
record_start = start;
var o = {},pn = this.paramNames;
o[pn.start] = start;
o[pn.limit] = this.pageSize;
this.store.load({params:o});
}
}),
// 添加與刪除頂端顯示工具條
tbar : new Ext.Toolbar(['-', {
text : '添加一行',
handler : function() {
var p = new Record({
stuId : '',
clsId: '1',
stuSex : '',
stuName : '',
stuAge : '',
stuAddr : '',
stuTel: ''
});
grid.stopEditing();
store.insert(0, p);
grid.startEditing(0, 2);
}
}, '-', {
text : '刪除一行',
handler : function() {
Ext.Msg.confirm('信息', '確定要?jiǎng)h除?', function(btn) {
if (btn == 'yes') {
var cells = sm.getSelections();
var jsonArray = [];
for (var i = 0; i < cells.length; i++) {
jsonArray.push(cells[i].data);
// store.remove(cells[i]);
}
Ext.lib.Ajax.request('POST', 'servlet/Del', {
success : function(response) {
Ext.Msg.alert('信息', response.responseText,
function() {
store.reload();
});
},
failure : function() {
Ext.Msg.alert("錯(cuò)誤", "與后臺(tái)聯(lián)系的時(shí)候出現(xiàn)了問(wèn)題");
}
}, 'data=' + encodeURIComponent(Ext.encode(jsonArray)));
}
});
}
}, '-', {
text: '保存',
handler: function(){
var m = store.modified.slice(0);
var jsonArray = [];
Ext.each(m, function(item) {
jsonArray.push(item.data);
});
Ext.lib.Ajax.request(
'POST',
'servlet/Save',
{success: function(response){
Ext.Msg.alert('信息', response.responseText, function(){
store.reload();
});
},failure: function(){
Ext.Msg.alert("錯(cuò)誤", "與后臺(tái)聯(lián)系的時(shí)候出現(xiàn)了問(wèn)題");
}},
'data=' + encodeURIComponent(Ext.encode(jsonArray))
);
}
}, '-']),
viewConfig : {
forceFit : true
}
});
store.load({
params : {
start : 0,
limit : 10
}
});
});
新建個(gè)index.jsp頁(yè)面 放入以下內(nèi)容:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>ExtJsDemo</title>
<link rel="stylesheet" type="text/css" href="ext/resources/css/ext-all.css">
<script type="text/javascript" src="ext/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="ext/ext-all-debug.js"></script>
<script type="text/javascript" src="ext/ext-fun.js"></script>
<script type="text/javascript" src="ext/PagingMemoryProxy.js"></script>
<script type="text/javascript" src="js/user.js"></script>
</head>
<body>
<div id="grid"></div>
</body>
</html>
配置下web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java./xml/ns/j2ee"
xmlns:xsi="http://www./2001/XMLSchema-instance"
xsi:schemaLocation="http://java./xml/ns/j2ee
http://java./xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>Query</servlet-name>
<servlet-class>ext.servlet.Query</servlet-class>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>Save</servlet-name>
<servlet-class>ext.servlet.Save</servlet-class>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>Del</servlet-name>
<servlet-class>ext.servlet.Del</servlet-class>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>GetCls</servlet-name>
<servlet-class>ext.servlet.GetCls</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Query</servlet-name>
<url-pattern>/servlet/Query</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Save</servlet-name>
<url-pattern>/servlet/Save</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Del</servlet-name>
<url-pattern>/servlet/Del</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>GetCls</servlet-name>
<url-pattern>/servlet/GetCls</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
上面的web.xml是自動(dòng)生成的......
后臺(tái)的實(shí)現(xiàn): dao
basedao:
package ext.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BaseDao {
public final String url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8";
public final String user = "root";
public final String pwd = "root";
private Connection conn = null;
private ResultSet rs = null;
public PreparedStatement pstm = null;
public BaseDao() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
*
* @Function getConnection()
* @return Connection
*/
public Connection getConnection() {
try {
conn = DriverManager.getConnection(url, user, pwd);
return conn;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
/**
*
* @Function closePreparedStatement()
*/
public void closePreparedStatement() {
try {
this.pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
*
* @Function closeConnection()
*/
public void closeConnection() {
try {
this.conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
*
* @Function exectueQuery()
* @param sql
* @return ResultSet
*/
public ResultSet exectueQuery(String sql) {
conn = this.getConnection();
try {
// pstm = conn.prepareStatement(sql);
rs = pstm.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
/**
*
* @Function executeUpdate()
* @throws SQLException
*/
public void executeUpdate() throws SQLException {
pstm.executeUpdate();
this.closePreparedStatement();
this.closeConnection();
}
/**
*
* @Function executeDelete()
* @throws SQLException
*/
public void executeDelete() throws SQLException {
pstm.executeUpdate();
this.closePreparedStatement();
this.closeConnection();
}
/**
*
* @Function executeInsert()
* @throws SQLException
*/
public void executeInsert() throws SQLException {
pstm.executeUpdate();
this.closePreparedStatement();
this.closeConnection();
}
/**
*
* @Function preparedStatement()
* @param sql
* @throws SQLException
*/
public void preparedStatement(String sql) throws SQLException {
conn = this.getConnection();
pstm = conn.prepareStatement(sql);
}
}
userdao:
package ext.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import ext.po.Clasz;
import ext.po.User;
public class UserDao extends BaseDao {
public UserDao() {
}
/**
*
* @Function getUser()
* @return List<User>
* @throws SQLException
*/
public List<User> getUser(int start, int limit) {
String sql = "select * from student LIMIT ?,?";
try {
this.preparedStatement(sql);
pstm.setInt(1, start);
pstm.setInt(2, limit);
} catch (SQLException e1) {
e1.printStackTrace();
}
List<User> list = new ArrayList<User>();
User user = null;
ResultSet rs = this.exectueQuery(sql);
try {
while (rs.next()) {
user = new User();
user.setStuId(rs.getInt("stu_id"));
user.setClsId(rs.getInt("cls_id"));
user.setStuName(rs.getString("stu_name"));
user.setStuSex(rs.getInt("stu_sex"));
user.setStuAge(rs.getInt("stu_age"));
user.setStuAddr(rs.getString("stu_addr"));
user.setStuTel(rs.getString("stu_tel"));
list.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}
this.closePreparedStatement();
this.closeConnection();
return list;
}
/**
*
* @return
*/
public int getCount() {
String sql = "select count(*) from student";
try {
this.preparedStatement(sql);
ResultSet rs = this.exectueQuery(sql);
while (rs.next()) {
return rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
/**
*
* @Function addUser()
* @param user
* @throws SQLException
*/
public void addUser(User user) throws SQLException {
String sql = "insert into student(cls_id,stu_name,stu_sex,stu_age,stu_addr,stu_tel) values(?,?,?,?,?,?)";
this.preparedStatement(sql);
pstm.setInt(1, user.getClsId());
pstm.setString(2, user.getStuName());
pstm.setInt(3, user.getStuSex());
pstm.setInt(4, user.getStuAge());
pstm.setString(5, user.getStuAddr());
pstm.setString(6, user.getStuTel());
this.executeInsert();
}
/**
*
* @Function editUser()
* @param user
* @throws SQLException
*/
public void editUser(User user) throws SQLException {
String sql = "update student set stu_name=?," + "stu_sex=?," + "stu_age=?," + "stu_addr=?," + "stu_tel=? "
+ "where stu_id=?";
this.preparedStatement(sql);
pstm.setString(1, user.getStuName());
pstm.setInt(2, user.getStuSex());
pstm.setInt(3, user.getStuAge());
pstm.setString(4, user.getStuAddr());
pstm.setString(5, user.getStuTel());
pstm.setInt(6, user.getStuId());
this.executeUpdate();
}
/**
*
* @Function deleteUser()
* @param user
* @throws SQLException
*/
public void deleteUser(Integer id) throws SQLException {
String sql = "delete from student where stu_id=?";
this.preparedStatement(sql);
pstm.setInt(1, id);
this.executeDelete();
}
/**
*
* function : 獲取班級(jí)列表
*
* @return
*
* @author wxl Jul 17, 2009
*/
public List<Clasz> getClassList() {
List<Clasz> list = new ArrayList<Clasz>();
String sql = "select * from class order by cls_cdate desc";
try {
this.preparedStatement(sql);
ResultSet rs = this.exectueQuery(sql);
while (rs.next()) {
Clasz cls = new Clasz();
cls.setClsId(rs.getInt("cls_id"));
cls.setClsName(rs.getString("cls_name"));
list.add(cls);
}
} catch (Exception ex) {
}
return list;
}
}
bo實(shí)現(xiàn):
package ext.bo;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import ext.dao.UserDao;
import ext.po.Clasz;
import ext.po.User;
public class UserBo {
/**
*
* function : 從數(shù)據(jù)庫(kù)獲取數(shù)據(jù)并轉(zhuǎn)化成json數(shù)據(jù)
*
* @param start
* 開始位置
* @param limit
* 每頁(yè)條數(shù)
* @return
*
* @author wxl Jul 16, 2009
*/
public String getJsonData(int start, int limit) {
UserDao uDao = new UserDao();
List<User> list = uDao.getUser(start, limit);
StringBuffer sb = new StringBuffer();
int count = uDao.getCount();
sb.append("{totalProperty:");
sb.append(count);
sb.append(",root:[");
for (User user : list) {
sb.append("{");
sb.append("stuId:" + user.getStuId() + ",");
sb.append("clsId:" + user.getClsId() + ",");
sb.append("stuSex:" + user.getStuSex() + ",");
sb.append("stuName:'" + user.getStuName() + "',");
sb.append("stuAge:" + user.getStuAge() + ",");
sb.append("stuAddr:'" + user.getStuAddr() + "',");
sb.append("stuTel:'" + user.getStuTel() + "'");
sb.append("},");
}
sb.append("]}");
return sb.substring(0, sb.lastIndexOf(",")) + sb.substring(sb.lastIndexOf(",") + 1);
}
/**
*
* function : 保存或修改數(shù)據(jù)
*
* @param data
*
* @author wxl Jul 17, 2009
*/
public void saveOrUpdate(String jsonData) {
UserDao uDao = new UserDao();
List<User> list = this.getUserFromJson(jsonData);
try {
if (list != null && list.size() > 0) {
for (User user : list) {
if (user.getStuId() != null && !"".equals(user.getStuId())) {
uDao.editUser(user);
} else {
uDao.addUser(user);
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
*
* function : 把Json數(shù)據(jù)轉(zhuǎn)化成List
*
* @param jsonData
* @return
*
* @author wxl Jul 17, 2009
*/
private List<User> getUserFromJson(String jsonData) {
List<User> list = new ArrayList<User>();
try {
org.json.JSONArray array = new JSONArray(jsonData);
for (int i = 0; i < array.length(); i++) {
org.json.JSONObject jo = new org.json.JSONObject(array.get(i).toString());
User uPo = new User();
// 班級(jí)id
uPo.setClsId(Integer.parseInt(jo.getString("clsId")));
// 住址
uPo.setStuAddr(jo.getString("stuAddr"));
// 年齡
String stuAge = jo.getString("stuAge");
if (stuAge != null && !"".equals(stuAge)) {
uPo.setStuAge(Integer.parseInt(stuAge));
} else {
uPo.setStuAge(0);
}
// 姓名
uPo.setStuName(jo.getString("stuName"));
// 性別
String stuSex = jo.getString("stuSex");
if (stuSex != null && !"".equals(stuSex)) {
uPo.setStuSex(Integer.parseInt(stuSex));
} else {
uPo.setStuSex(0);
}
// 電話
uPo.setStuTel(jo.getString("stuTel"));
// 學(xué)生id
String stuId = jo.getString("stuId");
if (stuId != null && !"".equals(stuId)) {
uPo.setStuId(Integer.parseInt(stuId));
}
list.add(uPo);
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
/**
*
* function : 刪除數(shù)據(jù)
*
* @param jsonData
*
* @author wxl Jul 17, 2009
*/
public void delUser(String jsonData) {
UserDao uDao = new UserDao();
List<User> list = this.getUserFromJson(jsonData);
try {
if (list != null && list.size() > 0) {
for (User user : list) {
if (user.getStuId() != null && !"".equals(user.getStuId())) {
uDao.deleteUser(user.getStuId());
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
*
*function: 獲取班級(jí)的json數(shù)據(jù)
*
* @return
*
*@author wxl Jul 17, 2009
*/
public String getClsJsonData() {
UserDao uDao = new UserDao();
List<Clasz> list = uDao.getClassList();
StringBuffer sb = new StringBuffer();
sb.append("[");
if (list != null && list.size() > 0) {
for (Clasz clasz : list) {
sb.append("['");
sb.append(clasz.getClsId() + "','");
sb.append(clasz.getClsName() + "'");
sb.append("],");
}
}
sb.append("]");
return sb.substring(0, sb.lastIndexOf(",")) + sb.substring(sb.lastIndexOf(",") + 1);
}
}
formbean::實(shí)現(xiàn)
package ext.po;
public class User {
private Integer stuId;
private Integer clsId;
private String stuName;
private Integer stuSex;
private Integer stuAge;
private String stuAddr;
private String stuTel;
public Integer getStuId() {
return stuId;
}
public void setStuId(Integer stuId) {
this.stuId = stuId;
}
public Integer getClsId() {
return clsId;
}
public void setClsId(Integer clsId) {
this.clsId = clsId;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public Integer getStuSex() {
return stuSex;
}
public void setStuSex(Integer stuSex) {
this.stuSex = stuSex;
}
public Integer getStuAge() {
return stuAge;
}
public void setStuAge(Integer stuAge) {
this.stuAge = stuAge;
}
public String getStuAddr() {
return stuAddr;
}
public void setStuAddr(String stuAddr) {
this.stuAddr = stuAddr;
}
public String getStuTel() {
return stuTel;
}
public void setStuTel(String stuTel) {
this.stuTel = stuTel;
另外個(gè)formbean:
package ext.po;
public class Clasz {
private Integer clsId;
private String clsName;
public Integer getClsId() {
return clsId;
}
public void setClsId(Integer clsId) {
this.clsId = clsId;
}
public String getClsName() {
return clsName;
}
public void setClsName(String clsName) {
this.clsName = clsName;
}
}
}
}
util實(shí)現(xiàn):
package ext.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JsonUtil {
/** *//**
* 從一個(gè)JSON 對(duì)象字符格式中得到一個(gè)java對(duì)象
*
* @param jsonString
* @param pojoCalss
* @return
*/
public static Object getObject4JsonString(String jsonString,Class pojoCalss) {
Object pojo;
JSONObject jsonObject = JSONObject.fromObject( jsonString );
pojo = JSONObject.toBean(jsonObject,pojoCalss);
return pojo;
}
/** *//**
* 從json HASH表達(dá)式中獲取一個(gè)map,改map支持嵌套功能
*
* @param jsonString
* @return
*/
public static Map getMap4Json(String jsonString) {
JSONObject jsonObject = JSONObject.fromObject( jsonString );
Iterator keyIter = jsonObject.keys();
String key;
Object value;
Map valueMap = new HashMap();
while( keyIter.hasNext())
{
key = (String)keyIter.next();
value = jsonObject.get(key);
valueMap.put(key, value);
}
return valueMap;
}
/** *//**
* 從json數(shù)組中得到相應(yīng)java數(shù)組
*
* @param jsonString
* @return
*/
public static Object[] getObjectArray4Json(String jsonString) {
JSONArray jsonArray = JSONArray.fromObject(jsonString);
return jsonArray.toArray();
}
/** *//**
* 從json對(duì)象集合表達(dá)式中得到一個(gè)java對(duì)象列表
*
* @param jsonString
* @param pojoClass
* @return
*/
public static List getList4Json(String jsonString, Class pojoClass) {
JSONArray jsonArray = JSONArray.fromObject(jsonString);
JSONObject jsonObject;
Object pojoValue;
List list = new ArrayList();
for ( int i = 0 ; i<jsonArray.size(); i++) {
jsonObject = jsonArray.getJSONObject(i);
pojoValue = JSONObject.toBean(jsonObject,pojoClass);
list.add(pojoValue);
}
return list;
}
/** *//**
* 從json數(shù)組中解析出java字符串?dāng)?shù)組
*
* @param jsonString
* @return
*/
public static String[] getStringArray4Json(String jsonString) {
JSONArray jsonArray = JSONArray.fromObject(jsonString);
String[] stringArray = new String[jsonArray.size()];
for( int i = 0 ; i<jsonArray.size() ; i++ ) {
stringArray[i] = jsonArray.getString(i);
}
return stringArray;
}
/** *//**
* 從json數(shù)組中解析出javaLong型對(duì)象數(shù)組
*
* @param jsonString
* @return
*/
public static Long[] getLongArray4Json(String jsonString){
JSONArray jsonArray = JSONArray.fromObject(jsonString);
Long[] longArray = new Long[jsonArray.size()];
for( int i = 0 ; i<jsonArray.size() ; i++ ) {
longArray[i] = jsonArray.getLong(i);
}
return longArray;
}
/** *//**
* 從json數(shù)組中解析出java Integer型對(duì)象數(shù)組
*
* @param jsonString
* @return
*/
public static Integer[] getIntegerArray4Json(String jsonString) {
JSONArray jsonArray = JSONArray.fromObject(jsonString);
Integer[] integerArray = new Integer[jsonArray.size()];
for( int i = 0 ; i<jsonArray.size() ; i++ ) {
integerArray[i] = jsonArray.getInt(i);
}
return integerArray;
}
/** *//**
* 從json數(shù)組中解析出java Date 型對(duì)象數(shù)組,使用本方法必須保證
*
* @param jsonString
* @return
*/
// public static Date[] getDateArray4Json(String jsonString,String DataFormat) {
//
// JSONArray jsonArray = JSONArray.fromObject(jsonString);
// Date[] dateArray = new Date[jsonArray.size()];
// String dateString;
// Date date;
//
// for( int i = 0 ; i<jsonArray.size() ; i++ ) {
// dateString = jsonArray.getString(i);
// date = DateUtil.stringToDate(dateString, DataFormat);
// dateArray[i] = date;
//
// }
// return dateArray;
// }
/** *//**
* 從json數(shù)組中解析出java Integer型對(duì)象數(shù)組
*
* @param jsonString
* @return
*/
// public static Double[] getDoubleArray4Json(String jsonString) {
//
// JSONArray jsonArray = JSONArray.fromObject(jsonString);
// Double[] doubleArray = new Double[jsonArray.size()];
// for( int i = 0 ; i<jsonArray.size() ; i++ ) {
// doubleArray[i] = jsonArray.getDouble(i);
//
// }
// return doubleArray;
// }
/** *//**
* 將java對(duì)象轉(zhuǎn)換成json字符串
*
* @param javaObj
* @return
*/
public static String getJsonString4JavaPOJO(Object javaObj) {
JSONObject json;
json = JSONObject.fromObject(javaObj);
return json.toString();
}
/** *//**
* 將java對(duì)象轉(zhuǎn)換成json字符串,并設(shè)定日期格式
*
* @param javaObj
* @param dataFormat
* @return
*/
// public static String getJsonString4JavaPOJO(Object javaObj , String dataFormat) {
//
// JSONObject json;
// JsonConfig jsonConfig = new JsonConfig(dataFormat);
// json = JSONObject.fromObject(javaObj,jsonConfig);
// return json.toString();
//
//
// }
}
刪除的servlet:
package ext.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ext.bo.UserBo;
public class Del extends HttpServlet {
/**
* 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 {
doPost(request, response);
}
/**
* 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 {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String jsonData = request.getParameter("data");
UserBo uBo = new UserBo();
uBo.delUser(jsonData);
response.getWriter().print("刪除成功!");
}
}
查詢班級(jí)的serlvet:
package ext.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ext.bo.UserBo;
public class GetCls extends HttpServlet {
/**
* 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 {
doPost(request, response);
}
/**
* 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 {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
UserBo uBo = new UserBo();
String jsonData = uBo.getClsJsonData();
response.getWriter().write(jsonData);
response.getWriter().flush();
}
}
查詢用戶的servlet:
package ext.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ext.bo.UserBo;
public class Query extends HttpServlet {
/**
* 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 {
doPost(request, response);
}
/**
* 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 {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String start = request.getParameter("start");
String limit = request.getParameter("limit");
UserBo uBo = new UserBo();
String json = uBo.getJsonData(Integer.parseInt(start), Integer.parseInt(limit));
response.getWriter().write(json);
response.getWriter().flush();
}
}
保存用戶servlet:
package ext.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ext.bo.UserBo;
public class Save extends HttpServlet {
/**
* 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 {
doPost(request, response);
}
/**
* 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 {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String data = request.getParameter("data");
UserBo uBo = new UserBo();
uBo.saveOrUpdate(data);
response.getWriter().print("保存或修改成功!");
}
}
相關(guān)的數(shù)據(jù)庫(kù)的創(chuàng)建:
創(chuàng)建數(shù)據(jù)表:
/*==============================================================*/
/* DBMS name: MySQL 5.0 */
/* Created on: 2009-7-13 19:08:37 */
/*==============================================================*/
drop table if exists class;
drop table if exists student;
/*==============================================================*/
/* Table: class */
/*==============================================================*/
create table class
(
cls_id int not null auto_increment,
cls_name varchar(20),
cls_cdate varchar(10),
primary key (cls_id)
);
/*==============================================================*/
/* Table: student */
/*==============================================================*/
create table student
(
stu_id int not null auto_increment,
cls_id int,
stu_name varchar(20),
stu_sex int,
stu_age int,
stu_addr text,
stu_tel varchar(20),
primary key (stu_id)
);
alter table student add constraint FK_Relationship_1 foreign key (cls_id)
references class (cls_id) on delete restrict on update restrict;
添加數(shù)據(jù)表:
insert into class values(null,'A班','2007-12-01');
insert into class values(null,'A班','2007-12-01');
insert into student values(null,1,'學(xué)生A',1,20,'福州','1111111');
insert into student values(null,2,'學(xué)生B',0,21,'福州','2222222');
insert into student values(null,1,'學(xué)生C',1,22,'福州','3333333');
insert into student values(null,2,'學(xué)生D',0,23,'福州','4444444');
insert into student values(null,1,'學(xué)生E',1,24,'福州','5555555');
insert into student values(null,2,'學(xué)生F',0,25,'福州','6666666');
insert into student values(null,1,'學(xué)生G',0,26,'福州','7777777');
insert into student values(null,2,'學(xué)生H',0,27,'福州','55055342555');
insert into student values(null,1,'學(xué)生I',0,18,'福州','55055333555');
insert into student values(null,1,'學(xué)生J',0,19,'福州','55055222555');
insert into student values(null,2,'學(xué)生K',0,19,'福州','55005551155');
insert into student values(null,2,'學(xué)生L',0,20,'福州','5055555555');
insert into student values(null,2,'學(xué)生M',1,21,'福州','5500055500055');
insert into student values(null,2,'學(xué)生N',1,23,'福州','55555523445');
insert into student values(null,2,'學(xué)生O',1,24,'福州','55530455555');
insert into student values(null,1,'學(xué)生P',1,25,'福州','55212055555');
insert into student values(null,1,'學(xué)生Q',1,24,'福州','5554450555');
insert into student values(null,1,'學(xué)生R',1,23,'福州','11111110');
insert into student values(null,2,'學(xué)生S',0,21,'福州','2222222');
insert into student values(null,1,'學(xué)生T',1,20,'福州','3333333');
insert into student values(null,1,'學(xué)生U',0,23,'福州','44444345404');
insert into student values(null,1,'學(xué)生V',1,24,'福州','5555555');
insert into student values(null,1,'學(xué)生W',1,19,'福州','5555565755');
insert into student values(null,1,'學(xué)生X',1,24,'福州','555553255');
insert into student values(null,2,'學(xué)生Y',1,22,'福州','555555634555');
insert into student values(null,2,'學(xué)生Z',1,22,'福州','5555522255');
insert into student values(null,2,'學(xué)生AA',1,18,'福州','55552342555');
insert into student values(null,1,'學(xué)生BB',1,17,'福州','5555523455');
insert into student values(null,1,'學(xué)生CC',0,24,'福州','5859404');
insert into student values(null,1,'學(xué)生DD',0,16,'福州','5553493');
insert into student values(null,1,'學(xué)生EE',0,16,'福州','5555555');
insert into student values(null,2,'學(xué)生FF',0,18,'福州','5553453');
insert into student values(null,2,'學(xué)生GG',1,17,'福州','5555533455');
insert into student values(null,1,'學(xué)生HH',1,18,'福州','5555234555');
運(yùn)行的結(jié)果如下:::