首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

SSH2 + JQuery EasyUI 干的一个对书籍增删改查的例子

2013-10-25 
SSH2 + JQuery EasyUI 做的一个对书籍增删改查的例子一、建Web Project,导入SSH2框架?二、在WebRoot下建给文

SSH2 + JQuery EasyUI 做的一个对书籍增删改查的例子

一、建Web Project,导入SSH2框架

?

二、在WebRoot下建给文件夹script,里面放入如下文件:

1.themes(可以给ui换主题)

2.jquery-1.8.0.min.js(可能会报错,不用管)

3.jquery.easyui.min.js

4.easyui-lang-zh_CN.js(国际化文件)

5.book.js(脚本)

?

三、entity和entity的映射文件

Book:

package org.ajax.entity;import java.sql.Timestamp;/** * Book entity. @author MyEclipse Persistence Tools */public class Book  implements java.io.Serializable {    // Fields         private Integer id;     private String isbn;     private String title;     private Double price;     private Timestamp pubdate;     private String intro;    // Constructors    /** default constructor */    public Book() {    }/** minimal constructor */    public Book(Double price, Timestamp pubdate) {        this.price = price;        this.pubdate = pubdate;    }        /** full constructor */    public Book(String isbn, String title, Double price, Timestamp pubdate, String intro) {        this.isbn = isbn;        this.title = title;        this.price = price;        this.pubdate = pubdate;        this.intro = intro;    }       // Property accessors    public Integer getId() {        return this.id;    }        public void setId(Integer id) {        this.id = id;    }    public String getIsbn() {        return this.isbn;    }        public void setIsbn(String isbn) {        this.isbn = isbn;    }    public String getTitle() {        return this.title;    }        public void setTitle(String title) {        this.title = title;    }    public Double getPrice() {        return this.price;    }        public void setPrice(Double price) {        this.price = price;    }    public Timestamp getPubdate() {        return this.pubdate;    }        public void setPubdate(Timestamp pubdate) {        this.pubdate = pubdate;    }    public String getIntro() {        return this.intro;    }        public void setIntro(String intro) {        this.intro = intro;    }}

?

Book.hbm.xml:

<?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="org.ajax.entity.Book" table="BOOK" schema="y2">        <id name="id" type="java.lang.Integer">            <column name="ID" length="200" />            <generator type="java.lang.String">            <column name="ISBN" length="100" />        </property>        <property name="title" type="java.lang.String">            <column name="TITLE" length="2048" />        </property>        <property name="price" type="java.lang.Double">            <column name="PRICE" precision="126" scale="0" not-null="true" />        </property>        <property name="pubdate" type="java.sql.Timestamp">            <column name="PUBDATE" length="11" not-null="true" />        </property>        <property name="intro" type="java.lang.String">            <column name="INTRO" length="4000" />        </property>    </class></hibernate-mapping>

?

?

四、dao和daoImpl

package org.ajax.dao;import java.util.List;import org.ajax.entity.Book;/** * 接口 *  * @author miao *  */public interface BookDao {/** * 查询所有书籍 *  * @return */public List<Book> find();/** * 添加书籍 *  * @param book * @return */public int add(Book book);/** * 删除书籍 *  * @param id * @return */public int delete(int id);/** * 获得一书籍记录 *  * @param id * @return */public Book findById(int id);/** * 更新书籍 *  * @param book * @return */public int update(Book book);/** * 统计书籍共多少本 *  * @return */public long findTotal();/** * 查询一页的数据 *  * @param begin 从哪条开始0 * @param end 得到多少条 * @param sort 排序字段 * @param order 升序或降序 desc/asc */public List<Book> findPageBooks(int begin, int end, String sort, String order);}

?

package org.ajax.dao.impl;import java.sql.SQLException;import java.util.List;import org.ajax.dao.BookDao;import org.ajax.entity.Book;import org.hibernate.Criteria;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.criterion.DetachedCriteria;import org.hibernate.criterion.Order;import org.springframework.orm.hibernate3.HibernateCallback;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;/** * 接口实现类 *  * @author miao *  */public class BookDaoImpl extends HibernateDaoSupport implements BookDao {@SuppressWarnings("unchecked")public List<Book> find() {DetachedCriteria criteria = DetachedCriteria.forClass(Book.class);criteria.addOrder(Order.desc("pubdate"));return super.getHibernateTemplate().findByCriteria(criteria);}public int add(Book book) {return (Integer) super.getHibernateTemplate().save(book);}public int delete(int id) {return super.getHibernateTemplate().bulkUpdate("delete from Book b where b.id=?", id);}public Book findById(int id) {return (Book) super.getHibernateTemplate().get(Book.class, id);}public int update(Book book) {return super.getHibernateTemplate().bulkUpdate("update Book b set b.isbn = ?, b.title = ?, b.price = ?,"+ "b.pubdate = ?, b.intro = ? where b.id = ?",new Object[] { book.getIsbn(), book.getTitle(), book.getPrice(), book.getPubdate(),book.getIntro(), book.getId() });}public long findTotal() {return (Long) super.getHibernateTemplate().execute(new HibernateCallback() {public Object doInHibernate(Session session) throws HibernateException, SQLException {return (Long) session.createQuery("select count(*) from Book").uniqueResult();}});}/** * 查询一页的数据 *  * @param begin 从哪条开始0 * @param end 得到多少条 * @param sort 排序字段 * @param order 升序或降序 desc/asc */@SuppressWarnings("unchecked")public List<Book> findPageBooks(final int begin, final int end, final String sort,final String order) {// 当要用到原生的Hibernate的Session的时候,这种最灵活,可以使用Query和Criteria,不用着急管理会话和事return super.getHibernateTemplate().executeFind(new HibernateCallback() {public Object doInHibernate(Session session) throws HibernateException, SQLException {Criteria criteria = session.createCriteria(Book.class);if ("desc".equals(order)) {criteria.addOrder(Order.desc(sort));} else {criteria.addOrder(Order.asc(sort));}criteria.setFirstResult(begin).setMaxResults(end);return criteria.list();}});}}

?

?

五、biz和bizImpl

package org.ajax.biz;import java.util.List;import org.ajax.entity.Book;/** * 业务类 *  * @author miao *  */public interface BookBiz {/** * 查询所有书籍 *  * @return */public List<Book> findAllBooks();/** * 添加书籍 *  * @param book * @return */public int addBook(Book book);/** * 删除书籍 *  * @param id * @return */public int deleteBook(int id);/** * 获得一书籍记录 *  * @param id * @return */public Book findBook(int id);/** * 更新书籍 *  * @param book * @return */public int updateBook(Book book);/** * 统计书籍共多少本 *  * @return */public long findTotal();/** * 查询一页的数据 *  * @param page 当前页号 * @param size 页面大小 * @param sort 排序字段 * @param order 升序或降序 desc/asc */public List<Book> findPageBooks(int page, int size, String sort, String order);}

?

package org.ajax.biz.impl;import java.util.List;import org.ajax.biz.BookBiz;import org.ajax.dao.BookDao;import org.ajax.entity.Book;/** * 业务实现类 *  * @author miao *  */public class BookBizImpl implements BookBiz {private BookDao bookDao;public void setBookDao(BookDao bookDao) {this.bookDao = bookDao;}public List<Book> findAllBooks() {return bookDao.find();}public int addBook(Book book) {return bookDao.add(book);}public int deleteBook(int id) {return bookDao.delete(id);}public Book findBook(int id) {return bookDao.findById(id);}public int updateBook(Book book) {return bookDao.update(book);}public long findTotal() {return bookDao.findTotal();}/** * 查询一页的数据 *  * @param page 当前页号 * @param size 页面大小 * @param sort 排序字段 * @param order 升序或降序 desc/asc */public List<Book> findPageBooks(int page, int size, String sort, String order) {int begin = (page - 1) * size;return bookDao.findPageBooks(begin, size, sort, order);}}

?

?

六、action

package org.ajax.action;import java.util.HashMap;import java.util.Map;import org.ajax.biz.BookBiz;import org.ajax.entity.Book;import com.opensymphony.xwork2.ActionSupport;/** * Action * @author miao * */public class BookAction extends ActionSupport {// 调用业务类private BookBiz bookBiz;private Book book; // 一本书private int page;// 当前第几页private Map<String, Object> data = new HashMap<String, Object>();// 封装数据private int size;// 页面大小,页面是rowsprivate String order;// 排序方向,desc和ascprivate String sort;// 排序属性名,如price// 标识操作是否成功private boolean operateSuccess;// set注入public void setBookBiz(BookBiz bookBiz) {this.bookBiz = bookBiz;}/* * 给easyui排序用的,表示排序方法 */public void setOrder(String order) {this.order = order;}/* * 给easyui排序用的,表示排序字段 */public void setSort(String sort) {this.sort = sort;}/* * 给easyui指定页面大小用的,如果要指定页面大小可变 * 页面是rows */public void setRows(int size) {this.size = size;}/* * 给easyui分页用的 */public void setPage(int page) {this.page = page;}// getter/setter方法public Book getBook() {return book;}public int getPage() {return page;}public Map<String, Object> getData() {return data;}public void setData(Map<String, Object> data) {this.data = data;}public int getRows() {return size;}public String getOrder() {return order;}public String getSort() {return sort;}public void setBook(Book book) {this.book = book;}public boolean isOperateSuccess() {return operateSuccess;}public void setOperateSuccess(boolean operateSuccess) {this.operateSuccess = operateSuccess;}/** * 查询某一页的书籍 */public String list() {data.clear();// 清除if (sort == null) {sort = "title";// 默认按书名排序}if (order == null) {order = "asc";// 默认按升序排序}data.put("rows", bookBiz.findPageBooks(page, size, sort, order));// 得到某一页的数据data.put("total", bookBiz.findTotal());// 得到所有的记录数return SUCCESS;}/** * 添加书籍 */public String addBook() {operateSuccess = (bookBiz.addBook(book) > 0);return SUCCESS;}/** * 更新书籍 */public String updateBook() {operateSuccess = (bookBiz.updateBook(book) > 0);return SUCCESS;}/** * 删除书籍 */public String deleteBook() {operateSuccess = (bookBiz.deleteBook(book.getId()) > 0);return SUCCESS;}/** * 查询一本书 */public String findBook() {book = bookBiz.findBook(book.getId());return SUCCESS;}}

?

?

七、spring配置文件

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.5.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-2.5.xsd"><!-- 数据源 --><bean id="dataSource" value="oracle.jdbc.driver.OracleDriver"></property><property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"></property><property name="username" value="y2"></property><property name="password" value="bdqn"></property></bean><!-- 会话工厂 --><bean id="sessionFactory"/></property><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop><prop key="show_sql">true</prop><prop key="format_sql">true</prop></props></property><property name="mappingResources"><list><value>org/ajax/entity/Book.hbm.xml</value></list></property></bean><!-- dao --><bean id="bookDao" ref="sessionFactory" /></bean><!-- biz --><bean id="bookBiz" ref="bookDao" /></bean><!-- action --><bean id="bookAction" ref="bookBiz" /></bean><!-- 配置事务 --><bean id="txManager"ref="sessionFactory" /></bean><!-- 定义事务通知 --><tx:advice id="txAdvice" transaction-manager="txManager"><tx:attributes><tx:method name="add*" propagation="REQUIRED" /><tx:method name="update*" propagation="REQUIRED" /><tx:method name="delete*" propagation="REQUIRED" /><tx:method name="find*" propagation="SUPPORTS" read-only="true" /></tx:attributes></tx:advice><!-- 定义哪些方法可以使用这些规则 --><aop:config><aop:pointcut id="bizMethod" expression="execution(* org.ajax.biz.*.*(..))" /><!-- 将事务通知与应用规则的方法组合 --><aop:advisor advice-ref="txAdvice" pointcut-ref="bizMethod" /></aop:config></beans>

?

?

八、struts配置文件

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"><struts><!-- 由spring管理 --><constant name="stuts.objectFactory" value="spring" /><!-- 打开开发模式 --><constant name="struts.devMode" value="true" /><package name="book" extends="json-default" namespace="/"><!-- 显示所有的书籍 --><action name="list" method="list"><!-- 指定的属性作为根元素输出 --><result type="json"><param name="root">data</param></result></action><!-- 添加书籍 --><action name="addBook" method="addBook"><result type="json" /></action><!-- 删除书籍 --><action name="deleteBook" method="deleteBook"><result type="json" /></action><!-- 得到一本书 --><action name="findBook" method="findBook"><result type="json" /></action><!-- 更新书籍 --><action name="updateBook" method="updateBook"><result type="json" /></action></package></struts>    

?

?

九、页面,book.jsp

<%@ page language="java" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme() + "://" + request.getServerName() + ":"+ request.getServerPort() + path + "/";%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.ddd"><html xmlns="http://www.w3.org/1999/xhtml"><head><base href="<%=basePath%>" /><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><link rel="stylesheet" type="text/css" href="script/themes/default/easyui.css" /><link rel="stylesheet" type="text/css" href="script/themes/icon.css" /><script type="text/javascript" src="script/jquery-1.8.0.min.js"></script><script type="text/javascript" src="script/jquery.easyui.min.js"></script><script type="text/javascript" src="script/easyui-lang-zh_CN.js"></script><link rel="stylesheet" href="style/book.css" type="text/css" /><script type="text/javascript" src="script/book.js"></script><title>书籍操作</title></head><body><div id="main"><table id="bookbody"></table></div><!-- 编辑数据的div,默认看不到 --><div id="divEdit"><div id="tabEdit"><form id="frmEdit"><input type="hidden" id="id" name="book.id" /><dl><dd>ISBN:</dd><dd><input type="text" size="15" id="isbn" name="book.isbn" /></dd></dl><dl><dd>书名:</dd><dd><input type="text" size="40" id="title" name="book.title" /></dd></dl><dl><dd>价格¥:</dd><dd><input type="text" size="10" id="price" name="book.price" /></dd></dl><dl><dd>出版日期:</dd><dd><input type="text" style="width: 150px" id="pubdate" name="book.pubdate" /></dd></dl><dl><dd>简介:</dd><dd><textarea cols="45" rows="3" id="intro" name="book.intro"></textarea></dd></dl></form></div></div></body></html>

?

?

十、脚本文件,book.js

//JQuery的入口$(function() {listBook();// 日期加上日期控件$("#pubdate").datebox({required : true});// 给文本框加上验证器$("#isbn").validatebox({required : true});// 书名的验证$("#title").validatebox({required : true,missingMessage : '书名不能为空'});// 价格用货币验证框$("#price").numberbox({required : true,min : 5.5,max : 9999,precision : 2,missingMessage : '请输入价格'});// 简介加验证$("#intro").validatebox({required : true});});// 加载书籍列表function listBook() {$("#bookbody").datagrid({width : 600,height : "auto",iconCls : 'icon-help', // 表格左上角的图标样式url : 'list.action', // 访问服务器的地址,要求返回JSON对象rownumbers : true, // 在最前面显示行号fitColumns : true, // 自动适应列宽pagination : true, // 在底部显示分页工具栏striped : true, // 隔行变色singleSelect : true, // 每次只选中一行loadMsg : '加载书籍列表ing……',pageSize : 5, // 指定每页的大小,服务器要加上page属性和total属性remoteSort : true, // 从服务器端排序,默认truepageList : [ 3, 5, 10 ], // 可以设置每页记录条数的列表,服务器要加上rows属性idField : 'id', // 主键属性toolbar : [ {// 工具栏text : '添加',iconCls : 'icon-add', // 图标handler : function() { // 处理函数addBook();}}, {text : '删除',iconCls : 'icon-cancel', // 图标handler : function() { // 处理函数deleteBook();}}, {text : '编辑',iconCls : 'icon-edit',// 图标handler : function() {// 处理函数editBook();}} ],columns : [ [ {field : 'isbn',title : 'ISBN',width : 70}, {field : 'title',title : '书籍名称',// 可以排序,但服务器也完成相应的代码,要加入sort和order属性sortable : true}, {field : 'price',title : '价格',align : 'right',width : 60,sortable : true,formatter : function(value) {return "$" + value;}}, {field : 'pubdate',title : '出版日期',sortable : true,formatter : function(value) {return value.substring(0, 10);}} ] ]});}// 显示编辑窗口function showEditForm() {$("#tabEdit").dialog({modal : true,// 模式窗口title : '书籍操作',iconCls : 'icon-save',buttons : [ {text : '确认',handler : function() {// 进行表单字段验证,当全部字段都有效时返回true和validatebox一起使用if ($('#frmEdit').form('validate')) {// 提交到服务器并写入数据库dealSave();// 关闭窗口closeForm();} else {$.messager.alert('验证', '书籍信息有误或不完整', 'error');}}}, {text : '取消',handler : function() {closeForm();}} ]});}// 关闭窗口function closeForm() {$("#frmEdit").form('clear');$('#tabEdit').dialog('close');}// 添加的函数function addBook() {// 清空原有的数据$('#frmEdit').form('clear');// 显示添加对话框showEditForm();}// 编辑按钮的操作function editBook() {var book = $('#bookbody').datagrid('getSelected');// 得到选中的一行数据// 如果没有选中记录if (book == null) {$.messager.alert('书籍', '请先选中要编辑的书籍', 'info');return;}$('#frmEdit').form('clear');// 填充数据$("#id").val(book.id);$("#isbn").val(book.isbn);$("#title").val(book.title);$("#price").numberbox("setValue", book.price);// 给默认值$("#pubdate").datebox("setValue", book.pubdate.substring(0, 10));$("#intro").val(book.intro);// 显示编辑页面showEditForm();}// 在增加和更新时点确定按钮的处理函数function dealSave() {// 表单数据序列化成一个字符串用&拼接var params = $("#frmEdit").serialize();// 得到id的值,为空串表示添加if ($("#id").val() == "") {$.post("addBook.action", params, function(result) {if (result.operateSuccess) {$('#bookbody').datagrid('reload');// 重新加载$.messager.alert('添加', '添加成功', 'info');} else {$.messager.alert('添加', '添加失败', 'warning');}});} else {// 表示更新$.post("updateBook.action", params, function(result) {if (result.operateSuccess) {$('#bookbody').datagrid('reload');// 重新加载$.messager.alert('更新', '更新成功', 'info');} else {$.messager.alert('更新', '更新失败', 'warning');}});}}// 删除书籍function deleteBook() {var book = $('#bookbody').datagrid('getSelected');// 得到选中的一行数据// 如果没有选中记录if (book == null) {$.messager.alert('删除', '请先选中要删除的书籍', 'info');return;}$.messager.confirm('确认', '真的要删除选中的记录吗?', function(r) {if (r) {var url = "deleteBook.action?book.id=" + book.id;// 试一下get方法(地址,回调函数)$.get(url, function(result) {if (result.operateSuccess) {$.messager.alert('删除', '选中的书籍成功删除!', 'info');// 重新加载$("#bookbody").datagrid('reload');} else {$.messager.alert('删除', '删除失败!', 'warning');}});}});}

?

?

十一、css,book.css

#divEdit {display: none;}* {font: 12px Arial;}div#main {margin: 0px auto;width: 600px;}#tabEdit input[type="text"],#tabEdit textarea {border: solid #66ccff 1px;}#tabEdit dl {padding-right: 35px;}

?

?

十二、demo

?JQuery-EasyUI-Book.zip

热点排行