Extjs4.1 MVC + servlet 小例子
我是extjs4.1初学者,求大虾别喷。这是我自己参考API中MVC写的小例子,extjs中的代码几乎和API没什么分别,就是添加了jsp servlet服务器的交互,英语能力好的还是推荐你看API,好了废话就说到这里了。
一、 项目结构:
这里由于extjs中的有自动加载的机制,所以项目的结果API给定了一个固定结构,这里借用一下API里面的结构图:
接下来就是我的项目结构图,于上图有一点点出入:
web目录:
java 的src目录:
index.html页面:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>index.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="extjs/resources/css/ext-all.css" type="text/css"></link> <!--<script type="text/javascript" src="extjs/ext-all.js"></script>--> <script type="text/javascript" src="extjs/ext-all-debug.js"></script> <script type="text/javascript" src="app.js"></script> </head> <body> </body> </html>
app.js
Ext.Loader.setConfig({enabled:true}); //Ext.loder 默认是不开启动态加载,这里是手动开启 Ext.application({ //定义命名控件 name :'AM', //应用程序的文件夹,例如:../app appFolder:'app', // 自动创建该类的一个实例 AM.view.Viewport //autoCreateViewport: true, //定义命名控件 controllers: [ 'Users' //定义Users控件的控制器,默认在app.controllers 路径下找Users.js ], //页面完全加载后将运行此方法 launch: function(){ //主容器 Ext.create('Ext.container.Viewport',{ layout: 'fit', items: [ { xtype:'userlist', } ] }); } });
容器的控制器 Users.js
//Users容器的控制器 Ext.define('AM.controller.Users', { extend: 'Ext.app.Controller', //定义数据源,默认在app.store下加载Users.js的数据源 stores: [ 'Users' ], //定义界面层,默认在app.view下加载Users下的List.js和Edit.js views:[ 'user.List', 'user.Edit' ], init: function() { //定义控制逻辑 this.control({ 'userlist': { itemdblclick: this.editUser //选项双击 }, 'useredit button[action=save]':{ click: this.updateUser //编辑框 点击save button } }); }, updateUser: function(button){ //console.log('clicked the Save button'); var win = button.up('window'), //获取button的window元素 form = win.down('form'), //获取表单form元素 record =form.getRecord(), //获取表单数据元素 values = form.getValues(); //获取该表单值 record.set(values); //修改当前的值 win.close(); //关闭编辑框 // this.getUsersStore().sync(); this.getStore("Users").sync(); //调用store update }, //record 当前表格的数据 editUser: function(grid,record){ //console.log('Double clicked on ' + record.get('name')); var view = Ext.widget('useredit'); //获取useredit编辑框实体 view.down('form').loadRecord(record); //读取表格里的数据(按照对应name属性来匹配) } /* , onPanelRendered: function() { console.log('The panel was rendered'); }*/ });
列表框 List.js:
//列表框 Ext.define('AM.view.user.List' ,{ extend: 'Ext.grid.Panel', alias: 'widget.userlist', //别名,用于Ext.create()和Ext.widget()创建,也可以用xtype创建 title:'All Users', //设置在控制层加载好的Users数据源, store: 'Users', initComponent:function(){ //初始化组件 /* //手动设置静态数据源 this.store = { fields:['name','email'], data : [ {name:'Ed',email:'ed@sencha.com'}, {name:'Tommy',email:'tommy@sencha.com'} ] }; */ this.columns = [ {header:'Name',dataIndex:'name',flex:1}, {header:'Email',dataIndex:'email',flex:1} ]; //调用父类方法 this.callParent(arguments); } });
编辑框 Edit.js
//编辑框 Ext.define('AM.view.user.Edit',{ extend: 'Ext.window.Window', alias: 'widget.useredit', title: 'Edit User', layout: 'fit', //自动显示 autoShow: true, //初始化 initComponent:function(){ this.items = [ { xtype:'form', items:[ { xtype:'textfield', name:'name', fieldLabel:'Name' }, { xtype: 'textfield', name:'email', fieldLabel:'Email' } ] } ]; this.buttons = [ { text: 'Save', action: 'save' }, { text:'Cancel', scope:this, handler:this.close } ]; this.callParent(arguments); } });
数据源 User.js
//数据源 Ext.define('AM.store.Users',{ extend: 'Ext.data.Store', //设置静态字段 //fields: ['name','email'], //加载数据model,默认在app.model下加载User.js model:'AM.model.User', //自动读取 autoLoad: true, //ajax代理 proxy:{ //设置访问类型 type: 'ajax', // url:'data/users.json', api:{ //向服务器读取数据 read:'/extjsProject/servlet/AjaxServlet?stype=2', //向服务器更新数据 update:'/extjsProject/servlet/AjaxServlet?stype=3' }, //定义格式 reader:{ type: 'json', root: 'users', successProperty:'success' } } /* //设置静态数据 data: [ {name:'Ed', email:'ed@sencha.com'}, {name:'Tommy', email:'tommy@sencha.com'} ]*/ });
数据model User.js
Ext.define('AM.model.User',{ extend: 'Ext.data.Model', //字段 fields: ['name','email'] });
好了页面的代码就到这里了
服务器:
AjaxServlet.java
在这里要注意:servelt里还用到了json的jar包,所以还要导入
json-lib-0.9.jar
json-lib-2.2.3-jdk15.jar
commons-beanutils-1.7.0.jar
commons-collections-3.2.jar
commons-lang-2.5.jar
commons-logging-1.1.1.jar
ezmorph-1.0.6.jar
相关jar导入好之后,接下来的就是代码:
package com.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; 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; import com.test.bean.JsonBean; import com.test.bean.User; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class AjaxServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("------> doGet()"); doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); int stype = Integer.parseInt(request.getParameter("stype")); User user1 = new User(1,"Ed","ed@sencha.com"); User user2 = new User(2,"Tommy","tommy@sencha.com"); switch(stype){ case 2: List list = new ArrayList(); list.add(user1); list.add(user2); JsonBean jsonBean = new JsonBean("users",list); response.getWriter().write(jsonBean.toString()); break; case 3: String json = getJson(request); System.out.println("-- " + json); JSONObject json1 = JSONObject.fromString(json); User user = (User) JSONObject.toBean(json1,User.class); System.out.println("├—— " + user.getId()+ " -- " + user.getName() + " -- " + user.getEmail()); break; } } /** * 描述: * 获取http 中 request 获取payload的内容(json) * @param request * @return * @throws IOException */ public static String getJson(HttpServletRequest request) throws IOException { String body = null; StringBuilder stringBuilder = new StringBuilder(); BufferedReader bufferedReader = null; try { InputStream inputStream = request.getInputStream(); if (inputStream != null) { bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); char[] charBuffer = new char[128]; int bytesRead = -1; while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { stringBuilder.append(charBuffer, 0, bytesRead); } } else { stringBuilder.append(""); } } catch (IOException ex) { throw ex; } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException ex) { throw ex; } } } body = stringBuilder.toString(); return body; } }
实体类User.java
package com.test.bean; public class User { private int id; private String name; private String email; public User(){}; public User(int id, String name, String email) { this.id = id; this.name = name; this.email = email; } 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 String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "id: " + id + "name: " + name + "email: " + email; } }
json格式处理类 jsonBean.java
package com.test.bean; import java.util.ArrayList; import java.util.List; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class JsonBean { private String rootData; private String root; private String success = "true"; public JsonBean(){}; public JsonBean(String success, String root, List rootData) { super(); this.success = success; this.root = root; this.rootData = getRootDataJson(rootData); } public JsonBean(String root, List rootData) { super(); this.root = root; this.rootData = getRootDataJson(rootData); } public String getSuccess() { return success; } public void setSuccess(String success) { this.success = success; } public String getRoot() { return root; } public void setRoot(String root) { this.root = root; } public String getRootData() { return rootData; } public void setRootData(String rootData) { this.rootData = rootData; } public void setRootDataList(List rootData) { this.rootData = getRootDataJson(rootData); } @Override public String toString() { if(root == null||root.equals("")){ throw new RuntimeException("root is null"); } String json = "{'success':"+success+",'"+root+"':"+rootData+"}"; System.out.println(json); return json; } private String getRootDataJson(List rootData){ if(rootData == null||rootData.size()==0){ throw new RuntimeException("rootData is null"); } JSONArray jsonList = JSONArray.fromObject(rootData); return jsonList.toString(); /*格式: * String str ="{'success':true,'users':[{'id':'1','name':'Ed','email':'ed@sencha.com'}," + "{'id':'2','name':'Tommy','email':'tommy@sencha.com'}]}"; */ } }
好了例子代码就到这里了!!如果有什么问题可以提出来一起学习,最后声明一下,我只是菜鸟,有什么错请大虾指出,勿喷。。。。