项目目录结构如下:
(1)index.html
<!DOCTYPE html> <html> <head> <title>用户管理</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="ext4/resources/css/ext-all.css"> <script type="text/javascript" src="ext4/ext-all.js"></script> <script type="text/javascript" src="ext4/ext-lang-zh_CN.js"></script> <script type="text/javascript" src="app.js"></script> </head> <body> </body> </html>
(2)app.js
Ext.Loader.setConfig({enabled:true}); Ext.application({ requires: [‘Ext.container.Viewport‘], name: ‘AM‘, appFolder: ‘app‘, controllers: [ ‘Users‘ ], launch: function(){ Ext.create(‘Ext.container.Viewport‘,{ layout: ‘fit‘, items: { xtype: ‘userlist‘ } }); } });
(3)controller/Users.js
Ext.define(‘AM.controller.Users‘, { extend: ‘Ext.app.Controller‘, models:[ ‘User‘ ], stores: [ ‘Users‘ ], views:[ ‘user.List‘, ‘user.Edit‘, ‘user.Add‘ ], init: function(){ this.control({ ‘viewport > userlist‘: { itemdblclick: this.editUser }, ‘useredit button[action=update]‘:{ click: this.updateUser }, ‘userlist button[action=add]‘:{ click: this.addUser }, ‘useradd button[action=create]‘:{ click: this.createUser }, ‘userlist button[action=destroy]‘:{ click: this.destroyUser } }); }, addUser: function(button){ var view = Ext.widget(‘useradd‘); view.show(); }, createUser: function(button){ var win = button.up(‘window‘); var form = win.down(‘form‘); Ext.Ajax.request({ url:‘/extjstest/UserServlet.do‘, params: form.getValues(), method: ‘POST‘, callback: function(options, success, response) { if(success){ win.close(); var responsejson = Ext.JSON.decode(response.responseText); var no = responsejson.no; Ext.Msg.confirm(‘操作结果!‘, responsejson.msg, function(btn) { if (no === ‘1‘ && btn === ‘yes‘) { Ext.widget(‘userlist‘).store.load(); } }); }else{ Ext.Msg.confirm(‘操作失败!‘, ‘请求超时或网络故障,错误编号:[‘ + response.status + ‘]是否要重新发送?‘, function(btn) { if (btn === ‘yes‘) { Ext.Ajax.request(options); } }); } } }); }, destroyUser: function(button){ var rowSelectionModel = Ext.widget(‘userlist‘).getSelectionModel(); if (rowSelectionModel.hasSelection()) { var records = rowSelectionModel.getSelection(); var len = records.length; var idarr = new Array(); for(var i=0;i<len;i++){ idarr[i] = records[i].get(‘id‘); } var idarrjson = Ext.JSON.encode(idarr);//转换成JSON格式 Ext.MessageBox.confirm(‘提示信息‘, ‘<font color=red>您确定删除所选中的信息?</font>‘, showResult); function showResult(btn){ if(btn===‘yes‘){ Ext.Ajax.request({ url: ‘/extjstest/UserServlet.do‘, params: { oprtype: ‘destroy‘, idarrjson: idarrjson }, method: ‘POST‘, callback: function(options, success, response) { if (success) { var responsejson = Ext.JSON.decode(response.responseText); var no = responsejson.no; Ext.Msg.confirm(‘操作结果提醒!‘, responsejson.msg, function(btn) { if (no === ‘1‘ && btn === ‘yes‘) { Ext.widget(‘userlist‘).store.load(); } }); } else { Ext.Msg.confirm(‘操作失败!‘, ‘请求超时或网络故障,错误编号:[‘ + response.status + ‘]是否要重新发送?‘, function(btn) { if (btn === ‘yes‘) { Ext.Ajax.request(options); } }); } } }); } } }else{ Ext.MessageBox.alert(‘信息提示‘, ‘<font color=red>请选择您要删除的行!</font>‘); } }, editUser: function(grid,record){ var view = Ext.widget(‘useredit‘); view.down(‘form‘).loadRecord(record); }, updateUser: function(button){ var win = button.up(‘window‘); var form = win.down(‘form‘); var record = form.getRecord(); //取出表单关联的 record var values = form.getValues(); //取出表单中的值 record.set(values); //把表单值设置到对应的 record win.close();//关闭窗口 //此种方式更新数据将采用json数据格式把参数发送到服务端,服务端接受此种参数时不能使用 //传统的request.getParameter()的方式,其参数是通过Request Payload传递给服务端的, //服务端只能通过读入request的字符流,通过解析json来获取参数值 this.getUsersStore().sync(); } });
(4)model/User.js
Ext.define(‘AM.model.User‘, { extend: ‘Ext.data.Model‘, fields: [‘id‘,‘name‘,‘email‘] });
(5)store/Users.js
Ext.define(‘AM.store.Users‘, { extend: ‘Ext.data.Store‘, model: ‘AM.model.User‘, autoLoad: true,//Store生成之后会自动让Proxy加载数据 proxy: { type: ‘ajax‘, api:{ read: ‘/extjstest/UserServlet.do?oprtype=read‘, update: ‘/extjstest/UserServlet.do?oprtype=update‘ }, reader: {//reader负责将response解码成store能理解的形式 type: ‘json‘, root: ‘users‘ } } });
(7)view/user/List.js
Ext.define(‘AM.view.user.List‘, { extend: ‘Ext.grid.Panel‘, alias: ‘widget.userlist‘, title: ‘用户列表‘, columnLines: true, loadMask: true, store: ‘Users‘, selModel: Ext.create(‘Ext.selection.CheckboxModel‘,{ checkOnly :true }),//复选框 initComponent: function(){ this.columns = [ Ext.create(‘Ext.grid.RowNumberer‘, {text: ‘行号‘, width: 35}), {header:‘ID‘, dataIndex:‘id‘, flex:1}, {header:‘NAME‘, dataIndex:‘name‘, flex:1}, {header:‘EMAIL‘, dataIndex:‘email‘, flex:1} ]; this.dockedItems = [ { xtype: ‘toolbar‘, dock: ‘top‘, items: [ { xtype: ‘button‘, text: ‘添加‘, action:‘add‘ }, ‘-‘, { xtype: ‘button‘, text: ‘删除‘, action: ‘destroy‘ } ] } ]; this.callParent(arguments); } });
(8)view/user/Add.js
Ext.define(‘AM.view.user.Add‘, { extend: ‘Ext.window.Window‘, alias: ‘widget.useradd‘, title: ‘添加用户‘, layout: ‘fit‘, autoShow: true, initComponent: function(){ this.items = [ { xtype: ‘form‘, items: [ { xtype: ‘textfield‘, name: ‘name‘, fieldLabel: ‘名称‘ }, { xtype: ‘textfield‘, name: ‘email‘, fieldLabel: ‘邮箱‘ }, { xtype: ‘hidden‘, name: ‘oprtype‘, value: ‘create‘ } ] } ]; this.buttons = [ { text: ‘保存‘, action: ‘create‘ }, { text: ‘取消‘, scope: this, handler: this.close } ]; this.callParent(arguments); } });
(9)view/user/Edit.js
Ext.define(‘AM.view.user.Edit‘, { extend: ‘Ext.window.Window‘, alias: ‘widget.useredit‘, title: ‘编辑用户信息‘, layout: ‘fit‘, autoShow: true, initComponent: function(){ this.items = [ { xtype: ‘form‘, items: [ { xtype: ‘hidden‘, name: ‘id‘ }, { xtype: ‘textfield‘, name: ‘name‘, fieldLabel: ‘姓名‘ }, { xtype: ‘textfield‘, name: ‘email‘, fieldLabel: ‘邮箱‘ } ] } ]; this.buttons = [ { text:‘保存‘, action:‘update‘ }, { text: ‘取消‘, scope: this, handler: this.close } ]; this.callParent(arguments); } });
(10)UserServlet.java
package com.yan.servlet; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author y */ public class UserServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String oprtype = request.getParameter("oprtype"); StringBuilder sb = new StringBuilder(); try (PrintWriter out = response.getWriter()) { Gson gson = new Gson(); switch(oprtype){ case "read": sb.append("{\"users\":") .append(gson.toJson(getUserList(), new TypeToken<List<User>>(){}.getType())) .append("}"); break; case "update": StringBuilder json = new StringBuilder(); String line; BufferedReader reader = request.getReader(); while((line=reader.readLine())!=null){ json.append(line); } User user = gson.fromJson(json.toString(), User.class); System.out.println("id:"+user.id); System.out.println("name:"+user.name); System.out.println("email:"+user.email); sb.append("{\"no\":\"1\",\"msg\":\"成功\"}"); break; case "create": System.out.println("name:"+request.getParameter("name")); System.out.println("email:"+request.getParameter("email")); sb.append("{\"no\":\"1\",\"msg\":\"成功\"}"); break; case "destroy": String idarrjson = request.getParameter("idarrjson"); List<String> ids = gson.fromJson(idarrjson, new TypeToken<List<String>>(){}.getType()); System.out.println(ids); sb.append("{\"no\":\"1\",\"msg\":\"成功\"}"); break; } out.print(sb.toString()); out.close(); } } List<User> getUserList(){ List<User> list = new ArrayList<>(); User user = new User(100,"张三","[email protected]"); list.add(user); user = new User(101,"李四","[email protected]"); list.add(user); user = new User(102,"王五","[email protected]"); list.add(user); user = new User(103,"王五","[email protected]"); list.add(user); return list; } public static final class User{ public int id; public String name; public String email; public User(int id,String name,String email){ this.id = id; this.name = name; this.email = email; } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } }
效果图:
时间: 2024-10-12 07:25:39