目录结构
这两个为Extjs框架代码,可从网上搜索下载
index.html代码如下
<!DOCTYPE html > <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=9"> <script type="text/javascript" src="Ext4.2/ext-all.js"></script> <script type="text/javascript" src="Ext4.2/ext-lang-zh_CN.js"></script> <link rel="stylesheet" type="text/css" href="Ext4.2/resources/css/ext-all-neptune.css"> <script type="text/javascript" src="my.js"></script> </head> <body> <div id="grid"></div> </body> </html>
my.js代码如下
Ext.onReady(function(){ Ext.QuickTips.init(); Ext.Loader.setConfig({ enabled:true }); Ext.application({ name : 'AM',//全局名称 appFolder : "my",//对应目录 launch:function(){ Ext.create('Ext.container.Viewport', { //创建Viewport layout:'auto',//自动布局 items: { xtype: 'userview', title: 'Users', html : '' } }); }, controllers:[ 'UserCl' ] }); });
UserView.js代码如下
Ext.define("AM.view.UserView", { extend : 'Ext.grid.Panel', alias : 'widget.userview',// 别名(widget.~~~)固定写法 store : 'UserStore',// 数据源 //renderTo : 'grid',// 指定元素的id, 一个DOM元素或现有的元素,这个组件将被渲染成 frame : true,// 面板渲染 //forceFit : true,//自动填充Panel空白处 columns : [ {//columns它定义了在表格中出现的所有列 text : '编号', dataIndex : 'id',// 数据来源的定义 align : 'center', width : 55, }, { text : '账号', width : 200, dataIndex : 'name',// 数据来源的定义 align : 'center', field : {// 文本编辑器 xtype : 'textfield',// 默认的文本字段编辑值 allowBlank : true // 提供是否非空的文本验证 } }, { text : '密码1', width : 155, dataIndex : 'pass',// 数据来源的定义 align : 'center', //flex : 1,// 占满剩余的空间 field : {// 文本编辑器 xtype : 'textfield',// 默认的文本字段编辑值 allowBlank : true // 提供是否非空的文本验证 } },{ text : '查看账号', width : 100, xtype : 'actioncolumn', items : [{ icon:'my/view/img/shequ1.png', tooltip : '内容', handler : function(grid, rowIndex, colIndex) { var rec = grid.getStore().getAt(rowIndex); alert(rec.get('name')); } }] } ], tbar : [//Top Bar'的缩略形式。 { icon:'my/view/img/add.png',//图片路径 xtype : 'button',// 添加按钮 text : '添加', id : 'add' }, { icon:'my/view/img/del.png', xtype : 'button',// 删除按钮 id : 'delete',// text : '删除', }, { xtype : 'label', text : '请输入搜索的账号:' },// 搜素框 { xtype : 'textfield', id : 'KeyWord' }, { icon:'my/view/img/shequ1.png', text : '搜索', id : 'sousu' }, ], plugins : [//插件 Ext.create('Ext.grid.plugin.RowEditing', {//可编辑插件 saveBtnText : '保存', cancelBtnText : "取消", autoCancel : false, clicksToEdit : 2, // 双击进行修改 1-单击 2-双击 0-可取消双击/单击事件 listeners : { edit : function(editor, e) { var myMask = new Ext.LoadMask(Ext.getBody(), { msg : '正在修改,请稍后...', }); myMask.show();// 显示组件'正在修改,请稍后...' //提交到后台 Ext.Ajax.request({// 修改 url : 'user!upDateByEntity',// 向服务器发送请求时默认使用的URL。 method : 'POST',// 默认使用的HTTP请求方式。注意,这个配置项是大小写敏感的,所有字母都应该大写 timeout : 2000,// 请求的超时时间,单位毫秒。默认为30000。 params : { "user.id" : e.record.get('id'), "user.name" : e.record.get('name'), "user.pass" : e.record.get('pass') }, //成功后执行的方法 success : function(response) { e.record.commit();// myMask.hide();// 隐藏组件'正在修改,请稍后...' Ext.Msg.alert("提示", "执行成功!"); } }); } } }) ], selType : 'checkboxmodel',// 设定选择模式 multiSelect : true,// 是否可以多选(多选框) autoScroll : true,// 自动显示滚动条 titleCollapse : true,// 允许通过单击Panel头部的任何位置实现Panel展开和折叠之间的切换 height : 500,// 高度 width : 600,// 宽度 dockedItems : [ {//dockedItems(他是组件)可以被安置在Panel的上方,右方,左方或者下方。 xtype : 'pagingtoolbar',//分页组件(这里也可以放按钮等组件) store : 'UserStore', //数据源 dock : 'bottom', //底部 displayInfo : true, //是否展示信息 firstText : '第一页', //显示第一页按钮快捷提示文本 lastText : '最后一页', //显示最后一页按钮快捷提示文本 prevText : '上一页', //显示上一页按钮快捷提示文本 nextText : '下一页', //显示下一页按钮快捷提示文本 refreshText : '刷新', //显示刷新按钮快捷提示文本 beforePageText : '第', //输入项前的文字 afterPageText : '页 共 {0} 页',//输入项后的文字 displayMsg: '第 {0} - {1} 条记录 共 {2} 条记录',// 显示分页状态的消息 emptyMsg: "没有数据", //没有数据时显示的消息 } ], initComponent : function() {//自动帮你引进你实例化对象的构成方法等 this.callParent(arguments); } });
Ext.define('AM.store.UserStore', { extend: 'Ext.data.Store', model : 'AM.model.UserModel', storeId: 'users',//当前store对象的唯一标识ID pageSize : 14,//分页:每页14条记录——默认是25条 proxy : {//代理 type : 'ajax', url : 'user!findByProperty', reader : {//阅读器 type : 'json', root : 'data',// totalProperty : 'totalCount'//从数据库中读取的总记录数 } }, autoLoad : true//自动加载 });
// 建立Usermodel // 建立一个store要使用的 model Ext.define('AM.model.UserModel',{ extend : 'Ext.data.Model', fields : [ {name : 'id', type : 'Integer'}, {name : 'name',type : 'string'}, {name : 'pass',type : 'string'} ] });
// 建立Usermodel // 建立一个store要使用的 model Ext.define('AM.model.UserModel',{ extend : 'Ext.data.Model', fields : [ {name : 'id', type : 'Integer'}, {name : 'name',type : 'string'}, {name : 'pass',type : 'string'} ] });
UserAction.java代码如下
package action; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import com.opensymphony.xwork2.ActionSupport; import dao.UserDao; import entity.User; public class UserAction extends ActionSupport { // ������Ҫ��ҳ����ܵ�ֵ private String name; private String pass; private Integer id; public int page; public int start; public int limit; public User user; // ʵ����� UserDao dao = new UserDao(); User u = new User(); // action��Ĭ�Ϸ��� public String execute() throws Exception { return SUCCESS; } // ����û� public String say() { u.setName(name); u.setPass(pass); dao.save(u); return SUCCESS; } // ɾ���û� public String delete() { String[] strArray = null; strArray = name.split(","); for (int i = 0; i < strArray.length; i++) { dao.delDate(strArray[i]); } return SUCCESS; } // ���û� public String upDateByEntity() { dao.upDate(user); return SUCCESS; } //��ҳ��ģ���ѯ public void findByProperty(){ UserDao dao=new UserDao(); HttpServletResponse response = org.apache.struts2.ServletActionContext.getResponse(); response.setContentType("text/html;charset=utf-8");// ���ñ��� List list= dao.findByProperty(page,limit,name); Gson g=new Gson();//json try { response.getWriter().write(( "{\"totalCount\":" + dao.findAll().size() + ",\",success\":true,\"data\":" + g.toJson(list) + "}")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //setter���� public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
package common.dao; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; /** * Hibrenate��session��ȡ�� * * */ public class HSessionFactory { private static String CONFIG_FILE_LOCATION = "hibernate.cfg.xml";//hibrenate�����ļ���·�� //������Ĭ��д��(�һ������������ǣ�������������) private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static Configuration configuration = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION; static { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private HSessionFactory() { } /** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return session factory * * session factory will be rebuilded in the next call */ public static void setConfigFile(String configFile) { HSessionFactory.configFile = configFile; sessionFactory = null; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; } }
package dao; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import uitl.ExportDB; import common.dao.HSessionFactory; import entity.User; public class UserDao { //��ȡhibrenate��session public Session getSession() { return HSessionFactory.getSession(); } Transaction tran = getSession().beginTransaction(); //��װhibrenate���뷽�� public void save(User user) { try { getSession().save(user); tran.commit(); } catch (Exception e) { e.printStackTrace(); } } //��װhibrenate�ķ��� public void upDate(User user){ try{ String hql = "update User r set r.name=?, r.pass=? where id="+user.getId(); System.out.println(hql);//������ Query query =getSession().createQuery(hql); query.setString(0, user.getName()); query.setString(1, user.getPass()); query.executeUpdate(); tran.commit(); }catch(HibernateException e){ e.printStackTrace(); } } //��װhibrenateɾ�� public void delDate(String user){ try{ String hql = "delete User where id="+user; System.out.println(hql);//������ Query query = getSession().createQuery(hql); query.executeUpdate(); tran.commit(); }catch(HibernateException e){ e.printStackTrace(); } } //(��װ��ҳ������ģ���ѯ) page���ǵڼ�ҳ limit����ÿҳ��������¼ public List findByProperty(int page,int limit,String name) { ExportDB tool = new ExportDB();//��������ʵ�� if(name==null)name=""; try { //��������where name like '%"+tool.getString(name)+"%' String queryString = "from User where name like '%"+tool.getString(name)+"%' order by id desc"; Query queryObject = getSession().createQuery(queryString); //hibrenate�ṩ�ķ�ҳ���� queryObject.setFirstResult((page-1)*limit);//��ʼλ�� queryObject.setMaxResults(limit);//ÿҳ��ʾ�ļ�¼ return queryObject.list(); } catch (RuntimeException re) { throw re; } } //��ѯ���� public List findAll() { try { String queryString = "from User"; Query queryObject = getSession().createQuery(queryString); return queryObject.list(); } catch (RuntimeException re) { throw re; } } }
package entity; public class User { //�������� private Integer id; private String name; private String pass; //��������Ĺ��췽�� public User(){} //�����в���Ĺ��췽�� public User(Integer id, String name, String pass) { super(); this.id = id; this.name = name; this.pass = pass; } //����get�� set���� public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } }
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="entity.User" table="my_user"> <id name="id" type="java.lang.Integer"> <column name="id"/> <generator class="native"/><!-- 不用管它先! --> </id> <property name="name" type="java.lang.String"> <column length="150" name="name"/> </property> <property name="pass" type="java.lang.String"> <column length="500" name="pass"/> </property> </class> </hibernate-mapping>
package uitl; import org.hibernate.cfg.Configuration; import org.hibernate.tool.hbm2ddl.SchemaExport; public class ExportDB { //������ݿ� public static void main(String[] args) { Configuration cfg = new Configuration().configure(); SchemaExport export = new SchemaExport(cfg); export.create(true, true); System.out.println("success"); } //ת�� public static String getString(String input){ String chinese=""; try { chinese=new String(input.getBytes("iso-8859-1"),"UTF-8"); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return chinese; } }hibernate.cfg.xml代码如下
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="dialect"> org.hibernate.dialect.OracleDialect </property> <property name="connection.url"> jdbc:oracle:thin:@127.0.0.1:1521:orcl </property> <property name="connection.username">你的oracle用户名</property> <property name="connection.password">你的oracle密码</property> <property name="connection.driver_class"> oracle.jdbc.driver.OracleDriver </property> <property name="myeclipse.connection.profile">RoleS</property> <property name="connection.autocommit">true</property> <property name="show_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <mapping resource="entity/User.hbm.xml" /> </session-factory> </hibernate-configuration>
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!--<package name="struts2" extends="struts-default" namespace="/"> <action name="role" class="action.role"> </action> </package> --> <constant name="struts.dveMode" value="true" /> <package name="struts2" extends="struts-default" namespace="/"> <action name="user_*" class="action.UserAction" method="{1}"> <result name="success">/success.jsp</result> </action> </package> </struts>