邵波的空间 的 Dwr-EditTable完整版
Dwr是Java领域一个著名的服务器端Ajax框架,借助Dwr的帮助,我们可以直接在客户端页面通过Javascript调用远程Java的方法。
看Dwr的示例中有一个EditTable的示例,觉得在实际使用中会非常的有用,就把此示例进行了扩展,实现与数据库的交互,在页面上可以直接添加用户、修改用户和删除用户操作。
数据库设计:
Java代码
- create table jackdemo1
- (
- id int primary key auto_increment,
- name varchar(50),
- age int,
- address varchar(200)
- );
-
create table jackdemo1
(
id int primary key auto_increment,
name varchar(50),
age int,
address varchar(200)
);
使用Dwr,首先要配置Web.xml文件:
Java代码
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <servlet>
- <servlet-name>dwr-invoker</servlet-name>
- <servlet-class>
- org.directwebremoting.servlet.DwrServlet
- </servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>dwr-invoker</servlet-name>
- <url-pattern>/dwr/*</url-pattern>
- </servlet-mapping>
- </web-app>
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>
org.directwebremoting.servlet.DwrServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
</web-app>
然后要在web.xml文件同一级目录下建立一个dwr.xml文件,具体的配置如下:
Java代码
- <!DOCTYPE dwr PUBLIC
- "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN"
- "http://getahead.org/dwr/dwr20.dtd">
- <dwr>
- <allow>
- <create javascript="People" creator="new">
- <param name="class" value="com.jack.dwr.simple.People"></param>
- </create>
- <convert match="com.jack.dwr.simple.Person" converter="bean" javascript="Person"></convert>
- </allow>
- </dwr>
<!DOCTYPE dwr PUBLIC
"-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN"
"http://getahead.org/dwr/dwr20.dtd">
<dwr>
<allow>
<create javascript="People" creator="new">
<param name="class" value="com.jack.dwr.simple.People"></param>
</create>
<convert match="com.jack.dwr.simple.Person" converter="bean" javascript="Person"></convert>
</allow>
</dwr>
其实Javascript="People"是要在客户端使用的对象名称,<param>是对象的Java类名,因为People类中对应的方法中使用了Person类,所在在这里要使用<convert>进行转换。
Person类是一个POJO类:
Java代码
- package com.jack.dwr.simple;
-
-
- public class Person {
- private int id;
- private String name;
- private int age;
- private String address;
-
- 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 getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
-
- public String getAddress() {
- return address;
- }
-
- public void setAddress(String address) {
- this.address = address;
- }
-
- }
package com.jack.dwr.simple;
public class Person {
private int id;
private String name;
private int age;
private String address;
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 getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
上面的各个属性对应数据库中的字段信息。
People类是对数据进行操作类也是就是具体的业务类:
Java代码
- package com.jack.dwr.simple;
-
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.ArrayList;
- import java.util.List;
-
- /**
- * A container for a set of people
- *
- * @author jackzhangyunjie
- */
- public class People {
- private Connection conn;
-
- /**
- * 构造函数,同时初始化建立与数据库的连接
- */
- public People() {
- try {
- conn = DBConnection.getConnectionMySqlDB("3306", "jackdemo",
- "root", "jack");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- /**
- * 删除一个用户
- *
- * @param person
- * 要删除的用户
- *
- */
- public void deletePerson(Person person) throws Exception {
- String sql = "delete from jackdemo1 where id=?";
- PreparedStatement pstmt = conn.prepareStatement(sql);
- pstmt.setInt(1, person.getId());
- //更新数据库操作
- pstmt.executeUpdate();
- //关闭预编译和数据库连接
- pstmt.close();
- conn.close();
- }
-
- /**
- * 更新用户信息
- * @param person 要进行更新的用户对象
- * @throws Exception
- */
- public void updatePerson(Person person) throws Exception {
- String sql = "update jackdemo1 set name=?,age=?,address=? where id=?";
- PreparedStatement pstmt = conn.prepareStatement(sql);
- pstmt.setString(1, person.getName());
- pstmt.setInt(2, person.getAge());
- pstmt.setString(3, person.getAddress());
- pstmt.setInt(4, person.getId());
- //更新数据库操作
- pstmt.executeUpdate();
- //关闭预编译和数据库连接
- pstmt.close();
- conn.close();
- }
-
- /**
- * 得到全部的人员信息
- *
- * @return 返回一个包含人员的List
- * @throws SQLException
- */
- @SuppressWarnings("unchecked")
- public List getAllPerson() throws SQLException {
- List list = new ArrayList();
- String sql = "select * from jackdemo1";
- Statement st = conn.createStatement();
- //查询数据库,得到所有人员信息
- ResultSet rs = st.executeQuery(sql);
- while (rs.next()) {
- Person person = new Person();
- person.setId(rs.getInt("id"));
- person.setName(rs.getString("name"));
- person.setAge(rs.getInt("age"));
- person.setAddress(rs.getString("address"));
- list.add(person);
- }
- return list;
- }
-
- /**
- * 添加人员
- *
- * @param person
- * 要添加的人员的信息
- */
- public void addPerson(Person person) throws Exception {
- String sql = "insert into jackdemo1(name,age,address) values(?,?,?)";
- PreparedStatement pstmt = conn.prepareStatement(sql);
- //设置人员信息
- pstmt.setString(1, person.getName());
- pstmt.setInt(2, person.getAge());
- pstmt.setString(3, person.getAddress());
- //更新数据库操作
- pstmt.executeUpdate();
- //关闭预编译和数据库连接
- pstmt.close();
- conn.close();
- }
- }
package com.jack.dwr.simple;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
* A container for a set of people
*
* @author jackzhangyunjie
*/
public class People {
private Connection conn;
/**
* 构造函数,同时初始化建立与数据库的连接
*/
public People() {
try {
conn = DBConnection.getConnectionMySqlDB("3306", "jackdemo",
"root", "jack");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除一个用户
*
* @param person
* 要删除的用户
*
*/
public void deletePerson(Person person) throws Exception {
String sql = "delete from jackdemo1 where id=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, person.getId());
//更新数据库操作
pstmt.executeUpdate();
//关闭预编译和数据库连接
pstmt.close();
conn.close();
}
/**
* 更新用户信息
* @param person 要进行更新的用户对象
* @throws Exception
*/
public void updatePerson(Person person) throws Exception {
String sql = "update jackdemo1 set name=?,age=?,address=? where id=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, person.getName());
pstmt.setInt(2, person.getAge());
pstmt.setString(3, person.getAddress());
pstmt.setInt(4, person.getId());
//更新数据库操作
pstmt.executeUpdate();
//关闭预编译和数据库连接
pstmt.close();
conn.close();
}
/**
* 得到全部的人员信息
*
* @return 返回一个包含人员的List
* @throws SQLException
*/
@SuppressWarnings("unchecked")
public List getAllPerson() throws SQLException {
List list = new ArrayList();
String sql = "select * from jackdemo1";
Statement st = conn.createStatement();
//查询数据库,得到所有人员信息
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
Person person = new Person();
person.setId(rs.getInt("id"));
person.setName(rs.getString("name"));
person.setAge(rs.getInt("age"));
person.setAddress(rs.getString("address"));
list.add(person);
}
return list;
}
/**
* 添加人员
*
* @param person
* 要添加的人员的信息
*/
public void addPerson(Person person) throws Exception {
String sql = "insert into jackdemo1(name,age,address) values(?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
//设置人员信息
pstmt.setString(1, person.getName());
pstmt.setInt(2, person.getAge());
pstmt.setString(3, person.getAddress());
//更新数据库操作
pstmt.executeUpdate();
//关闭预编译和数据库连接
pstmt.close();
conn.close();
}
}
以上就是具体的业务操作信息,其中
DBConnection.getConnectionMySqlDB("3306", "jackdemo","root", "jack")方法用于建立与数据库的连接。
DBConnection是一个数据库连接类:
Java代码
- package com.jack.dwr.simple;
-
- import java.sql.Connection;
- import java.sql.DriverManager;
-
- public class DBConnection {
- public static Connection getConnectionMySqlDB(String post, String dbName,String userName,String password)
- throws Exception {
- String driver = "com.mysql.jdbc.Driver";
- String url = "jdbc:mysql://localhost:" + post + "/" + dbName;
- String user = userName;
- String pwd = password;
- Class.forName(driver);
- return DriverManager.getConnection(url, user, pwd);
- }
- }
package com.jack.dwr.simple;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnection {
public static Connection getConnectionMySqlDB(String post, String dbName,String userName,String password)
throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:" + post + "/" + dbName;
String user = userName;
String pwd = password;
Class.forName(driver);
return DriverManager.getConnection(url, user, pwd);
}
}
当然你也可以自己扩展别的数据库连接方法。
具体的JSP页面:
<%@ page language="java" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>EditTable的完整扩展</title>
<script type="text/javascript" src="<%=path%>/dwr/util.js"></script>
<script type="text/javascript" src="<%=path%>/dwr/engine.js"></script>
<script type="text/javascript"
src="<%=path%>/dwr/interface/People.js"></script>
<script type="text/javascript" src="people.js"></script>
</head>
<body onload="init();">
<div id="tabContents">
<div id="demoDiv">
<h3>
All People
</h3>
<table border="1">
<thead>
<tr>
<th>
IDCode
</th>
<th>
Person
</th>
<th>
AGE
</th>
<th>
ADDRESS
</th>
<th>
Actions
</th>
</tr>
</thead>
<tbody id="peoplebody">
<tr id="pattern" style="display: none;">
<td>
<span id="tableId">Id</span>
</td>
<td>
<span id="tableName">Name</span>
</td>
<td>
<span id="tableAge">Age</span>
</td>
<td>
<span id="tableAddress">Address</span>
</td>
<td>
<input id="edit" type="button" value="Edit" onclick="editClicked(this.id)" />
<input id="delete" type="button" value="Delete" onclick="deleteClicked(this.id)" />
</td>
</tr>
</tbody>
</table>
<h3>
<input id="add" type="button" value="添加人员" onclick="addPerson();" />
</h3>
<div id="operation" style="display:none;">
<h3>
<span id="operationType"></span>
</h3>
<table class="plain">
<tr>
<td>
Name:
</td>
<td>
<input id="name" type="text" size="30" />
</td>
</tr>
<tr>
<td>
Age:
</td>
<td>
<input id="age" type="text" size="20" />
</td>
</tr>
<tr>
<td>
Address:
</td>
<td>
<input type="text" id="address" size="40" />
</td>
</tr>
<tr>
<td colspan="2" align="right">
<small>(ID=<span id="id">-1</span>)</small>
<input type="button" value="Save" onclick="writePerson()" />
<input type="button" value="Clear" onclick="clearPerson()" />
</td>
</tr>
</table>
</div>
</div>
</body>
</html>
上面是具体的页面信息,people.js信息如下:
Java代码
-
- var peopleCache = {};
- var viewed = -1;
- var type;
- function init() {
- fillTable();
- }
- function fillTable() {
- People.getAllPerson(function (people) {
- // Delete all the rows except for the "pattern" row
- dwr.util.removeAllRows("peoplebody", {filter:function (tr) {
- return (tr.id != "pattern");
- }});
- // Create a new set cloned from the pattern row
- var person, id;
- people.sort(function (p1, p2) {
- return p1.name.localeCompare(p2.name);
- });
- for (var i = 0; i < people.length; i++) {
- person = people[i];
- id = person.id;
- dwr.util.cloneNode("pattern", {idSuffix:id});
- dwr.util.setValue("tableId" + id, person.id);
- dwr.util.setValue("tableName" + id, person.name);
- dwr.util.setValue("tableAge" + id, person.age);
- dwr.util.setValue("tableAddress" + id, person.address);
- $("pattern" + id).style.display = ""; // officially we should use table-row, but IE prefers "" for some reason
- peopleCache[id] = person;
- }
- });
- }
- function editClicked(eleid) {
- alert(eleid);
- document.getElementById("operation").style.display = "block";
- document.getElementById("operationType").innerHTML = "\u7f16\u8f91\u6570\u636e";
- var person = peopleCache[eleid.substring(4)];
- dwr.util.setValues(person);
- type = "edit";
- }
- function addPerson() {
- document.getElementById("operation").style.display = "block";
- document.getElementById("operationType").innerHTML = "\u6dfb\u52a0\u6570\u636e";
- dwr.util.setValue("name", "");
- dwr.util.setValue("age", "");
- dwr.util.setValue("address", "");
- dwr.util.setValue("id", "?");
- type = "add";
- }
- //insert or update Person into database
- function writePerson() {
- var person;
- if (type == "add") {
- person = {name:null, age:null, address:null};
- dwr.util.getValues(person);
- dwr.engine.beginBatch();
- People.addPerson(person);
- }else if(type=="edit"){
- person = {id:null,name:null,age:null,address:null};
- dwr.util.getValues(person);
- dwr.engine.beginBatch();
- People.updatePerson(person);
- }
- fillTable();
- dwr.engine.endBatch();
- document.getElementById("operation").style.display = "none";
- dwr.util.setValue("name", "");
- dwr.util.setValue("age", "");
- dwr.util.setValue("address", "");
- dwr.util.setValue("id", "?");
- }
- //delete person from database
- function deleteClicked(eleid) {
- var person = peopleCache[eleid.substring(6)];
- dwr.engine.beginBatch();
- People.deletePerson(person);
- fillTable();
- dwr.engine.endBatch();
- }
var peopleCache = {};
var viewed = -1;
var type;
function init() {
fillTable();
}
function fillTable() {
People.getAllPerson(function (people) {
// Delete all the rows except for the "pattern" row
dwr.util.removeAllRows("peoplebody", {filter:function (tr) {
return (tr.id != "pattern");
}});
// Create a new set cloned from the pattern row
var person, id;
people.sort(function (p1, p2) {
return p1.name.localeCompare(p2.name);
});
for (var i = 0; i < people.length; i++) {
person = people[i];
id = person.id;
dwr.util.cloneNode("pattern", {idSuffix:id});
dwr.util.setValue("tableId" + id, person.id);
dwr.util.setValue("tableName" + id, person.name);
dwr.util.setValue("tableAge" + id, person.age);
dwr.util.setValue("tableAddress" + id, person.address);
$("pattern" + id).style.display = ""; // officially we should use table-row, but IE prefers "" for some reason
peopleCache[id] = person;
}
});
}
function editClicked(eleid) {
alert(eleid);
document.getElementById("operation").style.display = "block";
document.getElementById("operationType").innerHTML = "\u7f16\u8f91\u6570\u636e";
var person = peopleCache[eleid.substring(4)];
dwr.util.setValues(person);
type = "edit";
}
function addPerson() {
document.getElementById("operation").style.display = "block";
document.getElementById("operationType").innerHTML = "\u6dfb\u52a0\u6570\u636e";
dwr.util.setValue("name", "");
dwr.util.setValue("age", "");
dwr.util.setValue("address", "");
dwr.util.setValue("id", "?");
type = "add";
}
//insert or update Person into database
function writePerson() {
var person;
if (type == "add") {
person = {name:null, age:null, address:null};
dwr.util.getValues(person);
dwr.engine.beginBatch();
People.addPerson(person);
}else if(type=="edit"){
person = {id:null,name:null,age:null,address:null};
dwr.util.getValues(person);
dwr.engine.beginBatch();
People.updatePerson(person);
}
fillTable();
dwr.engine.endBatch();
document.getElementById("operation").style.display = "none";
dwr.util.setValue("name", "");
dwr.util.setValue("age", "");
dwr.util.setValue("address", "");
dwr.util.setValue("id", "?");
}
//delete person from database
function deleteClicked(eleid) {
var person = peopleCache[eleid.substring(6)];
dwr.engine.beginBatch();
People.deletePerson(person);
fillTable();
dwr.engine.endBatch();
}
以上就是全部的扩展内容。也可以通过附件下载运行看看效果。