extjs+servlet填充gird实现增删改查
由于项目工程中还有许多其他的练习,不好讲项目上传!
下面只说和本文章相关的代码
usergrid.jsp
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> <base href="<%=basePath%>"> <title>My JSP 'usergird.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <!--加载extjs4--> <link rel="stylesheet" type="text/css" href="ext4/resources/css/ext-all.css" /> <script type="text/javascript" src="ext4/ext-all-debug.js"></script> <!--ext4加载结束 --> <script type="text/javascript"> //下面两行代码必须要,不然会报404错误 Ext.Loader.setConfig({ enabled : true }); //我的searchGrid和ext4在同一目录下,所以引用时要到根目录去"../" Ext.Loader.setPath('Ext.ux', 'ext4/examples/ux'); //预加载 Ext.require([ 'Ext.grid.*', 'Ext.toolbar.Paging', 'Ext.data.*', 'Ext.ux.form.SearchField', //Checkbox需要引用 'Ext.selection.CheckboxModel', 'Ext.selection.CellModel', 'Ext.ux.CheckColumn' ] ); Ext .onReady(function() { var newFormWin; // 创建Model Ext.define('User', { extend : 'Ext.data.Model', fields : [ { name : 'id', mapping : 'id' }, { name : 'name', mapping : 'name' }, { name : 'sex', mapping : 'sex' }, { name : 'age', mapping : 'age' } ] }) // 创建数据源 var store = Ext.create('Ext.data.Store', { model : 'User', // 设置分页大小 pageSize : 5, proxy : { type : 'ajax', url : 'getUsersServlet', reader : { // 数据格式为json type : 'json', root : 'bugs', // 获取数据总数 totalProperty : 'totalCount' } }, autoLoad : true, actionMethods : { read : 'post' } }); //创建多选框 var checkBox = Ext.create('Ext.selection.CheckboxModel'); var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', { //表示“双击”才可以修改内容(取值只能为“1”或“2”) clicksToEdit : 2 } ); // 创建grid var grid = Ext .create( 'Ext.grid.Panel', { tbar : [ { xtype : 'button', text : '添加', handler : addFormWin }, { xtype : 'button', text : '修改', handler : edit_btn }, { xtype : 'button', text : '删除', handler : deleteUser } ], store : store, selModel : checkBox, columns : [ { text : '编号', width : 120, dataIndex : 'id', sortable : true }, { text : '姓名', width : 120, dataIndex : 'name', sortable : true }, { text : '性别', width : 120, dataIndex : 'sex', renderer:function(value){ if(value=='1'){ return '男'; }else{ return '女'; } }, sortable : true }, { text : '年龄', width : 120, dataIndex : 'age', sortable : true } ], height : 400, width : 480, x : 20, y : 40, title : 'ExtJS4 Grid分页查询示例示例', renderTo : 'grid', dockedItems : [ //多选框控件 { dock : 'top', xtype : 'toolbar', items : [ { itemId : 'Button', text : '显示所选', //tooltip:'Add a new row', //iconCls:'add', handler : function() { var record = grid .getSelectionModel() .getSelection(); if (record.length == 0) { Ext.MessageBox .show({ title : "提示", msg : "请先选择您要操作的行!" //icon: Ext.MessageBox.INFO }) return; } else { var ids = ""; for ( var i = 0; i < record.length; i++) { ids += record[i] .get("id") if (i < record.length - 1) { ids = ids + ","; } } Ext.MessageBox .show({ title : "所选ID列表", msg : ids }) } } } ] }, //添加搜索控件 { dock : 'top', xtype : 'toolbar', items : { width : 200, fieldLabel : '搜索姓名', labelWidth : 70, xtype : 'searchfield', store : store } }, { dock : 'bottom', xtype : 'pagingtoolbar', store : store, displayInfo : true, displayMsg : '显示 {0} - {1} 条,共计 {2} 条', emptyMsg : '没有数据' } ], // 分页功能 // bbar : Ext.create('Ext.PagingToolbar', { // store : store, // displayInfo : true, // displayMsg : '显示{0}-{1}条,共计{2}条', // emptyMsg : "没有数据" // }) }) //添加窗口 var userForm = new Ext.FormPanel({ // collapsible : true,// 是否可以展开 labelWidth : 75, // label settings here cascade unless overridden frame : true, bodyStyle : 'padding:5px 5px 0', waitMsgTarget : true, //reader : _jsonFormReader, // reader:new Ext.data.JsonReader({ // successProperty: 'success', // root: 'list' // }, // {name:'id',mapping:'id'}, // {name:'name',mapping:'name'}, // {name:'sex',mapping:'sex'}, // {name:'age',mapping:'age'} // ), defaults : { width : 230 }, defaultType : 'textfield', items : [ { fieldLabel : 'id', name : 'id', emptyText : 'id', hidden : true, hideLabel : true, allowBlank : true }, { fieldLabel : '用户名', name : 'name', emptyText : '用户名', allowBlank : false }, { fieldLabel : '年龄', name : 'age', emptyText : '年龄', xtype : 'numberfield', allowBlank : false }, new Ext.form.RadioGroup({ fieldLabel : '性别', name : 'sex', items : [ { boxLabel : '男', name : 'sex', inputValue : 1 }, { boxLabel : '女', name : 'sex', inputValue : 2 } ] }) ] }); store.loadPage(1); //添加窗口 function addFormWin() { // create the window on the first click and reuse on subsequent // clicks 判断此窗口是否已经打开了,防止重复打开 if (!newFormWin) { newFormWin = new Ext.Window({ // el : 'topic-win', layout : 'fit', width : 250, height : 250, closeAction : 'hide', plain : true, title : '添加用户', items : userForm, buttons : [ { text : '保存', disabled : false, handler : function() { addBtnsHandler(); newFormWin.hide(); } }, { text : '取消', handler : function() { userForm.form.reset();//清空表单 newFormWin.hide(); } } ] }); } newFormWin.show();//显示此窗口 } //添加窗口结束 //添加操作按钮 var addBtnsHandler = function() { if (userForm.form.isValid()) { userForm.form.submit({ url : 'addUserServlet', waitMsg : '正在保存数据,稍后...', success : function(form, action) { Ext.Msg.alert('保存成功', '添加用户信息成功!'); userForm.form.reset();//清空表单 grid.getStore().load(); newFormWin.hide(); }, failure : function(form, action) { Ext.Msg.alert('保存失败', '添加人员信息失败!'); } }); } else { Ext.Msg.alert('信息', '请填写完成再提交!'); } }; //修改操作开始========================================================================================================================== //点击修改按钮加载数据 function edit_btn(){ // var selectedKeys = grid.selModel.selections.keys;//returns array of selected rows ids only var selectedKeys = grid.getSelectionModel().getSelection(); //判断是否选中一行数据 没有选中提示没有选中,选中加载信息 if(selectedKeys.length != 1){ Ext.MessageBox.alert('提示','请选择一条记录!'); } //加载数据 else{ var EditUserWin = new Ext.Window({ title: '修改员工资料', //题头 layout:'fit',//布局方式 width:280,//宽度 height:200,//高度 plain: true,//渲染 items:userForm, //按钮 buttons: [{ text:'保存', handler:function(){ updateHandler(EditUserWin); } },{ text: '取消', handler: function(){ EditUserWin.hide(); } }] }); EditUserWin.show(); loadUser(); } } //加载数据 function loadUser(){ // var selectedKeys = grid.selModel.selections.keys;//returns array of selected rows ids only var selectedKeys = grid.getSelectionModel().getSelection(); var userId=selectedKeys[0].get("id"); Ext.Msg.alert(userId); userForm.form.load({ waitMsg : '正在加载数据请稍后',//提示信息 waitTitle : '提示',//标题 url : 'getUserServlet', params:{userId:userId}, method:'POST',//请求方式 success:function(form,action){ Ext.Msg.alert('提示','数据加载成功'); }, failure:function(form,action){//加载失败的处理函数 Ext.Msg.alert('提示','数据加载失败'); } }); } //修改按钮操作 function updateHandler(w){ if (userForm.form.isValid()) { userForm.form.submit({ clientValidation:true,//进行客户端验证 waitMsg : '正在提交数据请稍后...',//提示信息 waitTitle : '提示',//标题 url : 'updateUserServlet',//请求的url地址 method:'POST',//请求方式 success:function(form,action){//加载成功的处理函数 w.hide(); userForm.form.reset();//清空表单 grid.getStore().load(); Ext.Msg.alert('提示','修改信息成功'); }, failure:function(form,action){//加载失败的处理函数 Ext.Msg.alert('提示','ID不能修改'); Ext.Msg.alert('提示','修改信息失败'); } }); }else { Ext.Msg.alert('信息', '请填写完成再提交!'); } } //修改操作结束========================================================================================================================== //删除用户 function deleteUser() { //得到选中的行 var data = grid.getSelectionModel().getSelection(); Ext.Msg.alert(data); if (data.length == 0) { Ext.MessageBox.alert('提示', '请选择您要操作的行!'); } else { Ext.Msg .confirm( '请确认', '是否真的要删除数据', function(button, text) { if (button == "yes") { //用于存放所要删除的数据 var ids = []; //遍历并放入ids中 Ext.Array.each(data, function( record) { ids.push(record.data); }); alert(ids.length); Ext.Ajax .request( { url : 'deleteUserServlet', params : { //在后台接收deleteUsers为要删除的对象 deleteUsers : Ext .encode(ids) }, method : 'POST', success : function( response) { var success = Ext .decode(response.responseText).success; if (success) { Ext.Array .each( data, function( record) { //删除store中的数据,页面效果 store .remove(record); store .load(); } ); } else { Ext.MessageBox .show( '提示', '删除失败') } } }) } }); } } }) </script> </head> <div id="grid"></div> <body> </body> </html>
DBConnection.java
package com.nuoxin.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBConnection { private static Connection connection; private static Statement statement; private static ResultSet resultSet; public static Connection getConnection() { try { try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("加载驱动"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } connection = DriverManager .getConnection( "jdbc:mysql://localhost:3306/user", "root", "root"); } catch (SQLException e) { // TODO Auto-generated catch block System.out.println("数据库连接失败"); e.printStackTrace(); } return connection; } public static Statement getStatement() { try { statement = getConnection().createStatement(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return statement; } public static ResultSet getResultSet(String sql) { try { resultSet = getStatement().executeQuery(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return resultSet; } public static void close(){ if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (statement != null) { try { statement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) throws SQLException { ResultSet rs = getResultSet("select * from users"); while (rs.next()) { try { System.out.println(rs.getString("name")); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
UserSerivce.java
package com.iss.service; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.nuoxin.pojo.Users; import com.nuoxin.util.DBConnection; public class UserService { // 修改用户 public static void updateUser(Users user) { String sql = "update users set name='" + user.getName() + "',sex='" + user.getSex() + "',age='" + user.getAge() + "' where id=" + user.getId() + ""; try { Statement statement = DBConnection.getStatement(); statement.executeUpdate(sql); DBConnection.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 删除用户 public static void deleteUser(Users users) { String sql = "delete from users where id=" + users.getId() + ""; try { DBConnection.getStatement().executeUpdate(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } DBConnection.close(); } // 添加用户 public static void addUser(Users user) { String sql = "insert into users values(null,'" + user.getName() + "','" + user.getSex() + "','" + user.getAge() + "')"; try { DBConnection.getStatement().executeUpdate(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } DBConnection.close(); } public static Users getUser(int id) { String sql = "select * from users where id=" + id; Users user = null; ResultSet resultSet = DBConnection.getResultSet(sql); try { while (resultSet.next()) { user = new Users(); user.setId(resultSet.getInt("id")); user.setName(resultSet.getString("name")); user.setAge(resultSet.getString("sex")); user.setSex(resultSet.getString("age")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return user; } }
几个servlet
getUsersServlet
package com.nuoxin.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.LimitExceededException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.nuoxin.util.DBConnection;
public class GetUsersServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
StringBuilder stringBuilder;
String start = request.getParameter("start");
System.out.println("start:" + start);
String limit = request.getParameter("limit");
System.out.println("limit:" + limit);
String query = request.getParameter("query");
System.out.println(query);
// 判断条件
String countSql = "select count(*) from users ";
String selectSql = "select * from users limit " + start + "," + limit
+ "";
if (query != null && !"".equals(query)) {
query = new String(query.getBytes("iso-8859-1"), "utf-8");
System.out.println("query:" + query);
countSql += " where name=‘" + query + "‘;";
System.out.println(countSql);
selectSql = "select * from users where name=‘" + query + "‘ limit "
+ start + "," + limit + "";
System.out.println(selectSql);
}
int total = 0;
ResultSet resultSet = DBConnection.getResultSet(countSql);
// 添加异常快捷键 alt+shift+z
try {
while (resultSet.next()) {
total = resultSet.getInt(1);
System.out.println("total:" + total);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ResultSet rs = DBConnection.getResultSet(selectSql);
stringBuilder = new StringBuilder();
// 拼接json字符串 jdbc中下标从1开始
stringBuilder.append("{totalCount:" + total + ",bugs:[");
try {
while (rs.next()) {
stringBuilder.append("{");
stringBuilder.append("id:" + "\‘" + rs.getInt(1) + "\‘,");
stringBuilder.append("name:" + "\‘" + rs.getString(2) + "\‘,");
stringBuilder.append("sex:" + "\‘" + rs.getString(3) + "\‘,");
stringBuilder.append("age:" + "\‘" + rs.getString(4) + "\‘");
stringBuilder.append("},");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String json = null;
if (total != 0) {
json = stringBuilder.substring(0, stringBuilder.length() - 1);
}
// json = stringBuilder.substring(0, stringBuilder.length());
// json += "]}";
json = stringBuilder.append("]}").toString();
System.out.println("json:" + json);
out.print(json);
out.flush();
out.close();
}
}
getUserServlet 这个是修改用户时在userForm中加载用户
package com.nuoxin.servlet;
import java.io.IOException;
import java.io.PrintWriter;
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 com.iss.service.UserService;
import com.nuoxin.pojo.Users;
import com.nuoxin.util.DBConnection;
public class GetUserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
int userId = Integer.parseInt(request.getParameter("userId"));
System.out.println("userId:" + userId);
Users user = UserService.getUser(userId);
// JSONArray jsonArray = JSONArray.fromObject(user);
System.out.println("{success:true,data:" + user + "}");
out.print("{success:true,data:" + user + "}");
// out.print("{success:true,data:{age:‘22‘,id:46,name:‘22‘,sex:‘22‘}}");
out.flush();
out.close();
}
}
addUserSevlet
package com.nuoxin.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.iss.service.UserService;
import com.nuoxin.pojo.Users;
public class AddUserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String sex = request.getParameter("sex");
String age = request.getParameter("age");
Users user=new Users();
user.setName(name);
user.setSex(sex);
user.setAge(age);
System.out.println("name:"+user.getName());
UserService.addUser(user);
out.print("{success:true}");
out.flush();
out.close();
}
}
deleteUserServlet 这里要注意引入解析json的包
package com.nuoxin.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.iss.service.UserService;
import com.nuoxin.pojo.Users;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class DeleteUserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String deleteUsers = request.getParameter("deleteUsers");
System.out.println("deleteUsers:"+deleteUsers);
JSONArray jsonArray = JSONArray.fromObject(deleteUsers);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
UserService.deleteUser((Users) JSONObject.toBean(jsonObject,
Users.class));
}
out.print("{success:true}");
out.flush();
out.close();
}
}
updateUserServlet
package com.nuoxin.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.iss.service.UserService;
import com.nuoxin.pojo.Users;
import com.nuoxin.util.DBConnection;
public class UpdateUserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
int id = Integer.parseInt(request.getParameter("id"));
Users user = UserService.getUser(id);
user.setName(request.getParameter("name"));
user.setAge(request.getParameter("age"));
user.setSex(request.getParameter("sex"));
UserService.updateUser(user);
out.print("{success:true}");
out.flush();
out.close();
}
}
点击打开链接这是整个项目链接地址
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。