采用MCV框架:Model、Control、View
项目结构:
1. 设计表
2. 实体类
private int id;
private String bookid;
private String bookname;
private int bookprice;
private String author;
------get and set method------
﹂实体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">
<hibernate-mapping>
<class name="com.web.bean.BookInfo" table="booklist">
<id name="id" column="id" type="java.lang.Integer">
<generator class="identity"></generator>
</id>
<property name="bookid" column="bookid" type="java.lang.String"></property>
<property name="bookname" column="bookname" type="java.lang.String" />
<property name="bookprice" column="bookprice" type="java.lang.Integer" />
<property name="author" column="author" type="java.lang.String" />
</class>
</hibernate-mapping>
3. 持久接口
package com.web.dao;
import java.util.List;
import com.web.bean.BookInfo;
public interface BookDAO {
public void saveBook(BookInfo bookInfo);
public void delBook(BookInfo bookInfo);
public void delAllBook(int[] ids);
public void updateBook(BookInfo bookInfo);
public BookInfo findById(Integer id);
public List<BookInfo> showAllRecord(int page,final int size);
public int getCount();
}
4. 持久实现
package com.web.dao.impl;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.web.bean.BookInfo;
import com.web.dao.BookDAO;
public class BookDAOImpl extends HibernateDaoSupport implements BookDAO {
/**
* 删除多条记录
*/
public void delAllBook(int[] ids) {
List<BookInfo> bookInfo = new ArrayList<BookInfo>();
for(int i=0; i<ids.length;i++){
BookInfo book = this.findById(ids[i]);
bookInfo.add(book);
System.out.println("实现Book:" + book);
}
System.out.println("实现批量:" + bookInfo);
this.getHibernateTemplate().deleteAll(bookInfo);
}
/**
* 删除一条记录
*/
public void delBook(BookInfo bookInfo) {
this.getHibernateTemplate().delete(bookInfo);
}
/**
* 显示一条记录
*/
public BookInfo findById(Integer id) {
BookInfo bookInfo = (BookInfo) this.getHibernateTemplate().get(BookInfo.class, id);
System.out.println("实现实体id:" + id);
return bookInfo;
}
/**
* 保存记录
*/
public void saveBook(BookInfo bookInfo) {
this.getHibernateTemplate().save(bookInfo);
}
/**
* 显示所有记录
*/
@SuppressWarnings("unchecked")
public List<BookInfo> showAllRecord(int page,final int size) {
//String hql="from BookInfo";
//return (List<BookInfo>)this.getHibernateTemplate().find(hql);
if(page <= 0) {
page = 1;
}
final int curPage = page;
List list = getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query query = session.createQuery("from BookInfo");
List result = query.setFirstResult((curPage -1) * size).setMaxResults(size).list();
return result;
}
});
return list;
}
/**
* 更新记录
*/
public void updateBook(BookInfo bookInfo) {
this.getHibernateTemplate().update(bookInfo);
}
@SuppressWarnings("unchecked")
public int getCount(){
List list = getHibernateTemplate().executeFind(new HibernateCallback(){
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query query = session.createQuery("select count(*) from BookInfo");
return query.list();
}
});
return Integer.parseInt(list.get(0) + "");
}
}
5. 业务接口
package com.web.service;
import java.util.List;
import com.web.bean.BookInfo;
public interface BookService {
public void saveRecord(BookInfo bookInfo);
public void delRecord(BookInfo bookInfo);
public void updateRecord(BookInfo bookInfo);
public BookInfo showById(Integer id);
public List<BookInfo> showAll(int page,final int size);
public void delAll(int[] ids);
public int getBookCount();
}
6. 业务实现
package com.web.service.impl;
import java.util.List;
import com.web.bean.BookInfo;
import com.web.dao.BookDAO;
import com.web.service.BookService;
public class BookServiceImpl implements BookService {
private BookDAO bookDAO;
public BookDAO getBookDAO() {
return bookDAO;
}
public void setBookDAO(BookDAO bookDAO) {
this.bookDAO = bookDAO;
}
public void delAll(int[] ids) {
this.bookDAO.delAllBook(ids);
}
public void delRecord(BookInfo bookInfo) {
this.bookDAO.delBook(bookInfo);
}
public void saveRecord(BookInfo bookInfo) {
this.bookDAO.saveBook(bookInfo);
}
public List<BookInfo> showAll(int page,final int size) {
return this.bookDAO.showAllRecord(page,size);
}
public BookInfo showById(Integer id) {
return this.bookDAO.findById(id);
}
public void updateRecord(BookInfo bookInfo) {
this.bookDAO.updateBook(bookInfo);
}
public int getBookCount(){
return this.bookDAO.getCount();
}
}
7. utiliy功能
package com.web.utiliy;
/**
* 分页类
*
*/
public class SitePage {
private int pageCount;//总共页数
private int pageSize;//每页显示数量
private int recordCount;//记录总数
private int currentPage;//当前页数
private String pageUrl;//当前url地址
/**
* 默认构造器
*/
public SitePage() {
this.pageCount = 0;
this.pageSize = 3;
this.recordCount = 0;
this.currentPage = 1;
this.pageUrl = "showBook";
}
/**
* 设置每页显示数量
* @param pageSize
*/
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
/**
* 设置记录总数
* @param recordCount
*/
public void setRecordCount(int recordCount) {
this.recordCount = recordCount;
}
/**
* 设置当前页数
* @param currentPage
*/
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
/**
* 设置当前url地址
* @param pageUrl
*/
public void setPageUrl(String pageUrl) {
this.pageUrl = pageUrl;
}
/**
* 获取分页总数
* @return Integer
* @throws Exception
*/
private int getPageCount() throws Exception {
//如果每页显示数量小于或等于0,抛出错误异常
if(this.pageSize <= 0) {
throw new Exception("每页显示数量必须大于零");
}
//计算分页总数
if(this.recordCount % this.pageSize == 0)
this.pageCount = this.recordCount / this.pageSize;
else
this.pageCount = this.recordCount / this.pageSize + 1;
if(this.pageCount == 0) {
this.pageCount = 1;
}
return this.pageCount;
}
/**
* 获得分页展示
* @return
* @throws Exception
*/
public String getPage() throws Exception {
//获取分页总数
getPageCount();
String pageStr = "";
//设置上一页
if(this.currentPage > 1 && this.pageCount > 1) {
pageStr += "<a href=\""+ this.pageUrl +"?page="+ (this.currentPage -1 ) +"\"><</a>";
}
else {
pageStr += "<span class=\"disabled\"><</span>";
}
//中间页数
for(int i = (this.currentPage - 6);i < (this.currentPage + 6);i++) {
if(i > 0 && i <= this.pageCount) {
if(this.currentPage == i) {
pageStr += "<span class=\"current\">"+ i +"</span>";
}
else {
pageStr += "<a href=\""+ this.pageUrl +"?page="+ i +"\">"+ i +"</a>";
}
}
}
//下一页
if(this.currentPage < this.pageCount) {
pageStr += "<a href=\""+ this.pageUrl +"?page="+ (this.currentPage + 1 ) +"\">></a>";
}
else {
pageStr += "<span class=\"disabled\">></span>";
}
return pageStr;
}
}
8. 表现活动
package com.web.action;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.web.bean.BookInfo;
import com.web.service.BookService;
import com.web.utiliy.SitePage;
@SuppressWarnings("serial")
public class BookAction extends ActionSupport {
private BookInfo bookInfo;
private BookService bookService;
private int[] ids;
private String page;
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public int[] getIds() {
return ids;
}
public void setIds(int[] ids) {
this.ids = ids;
}
public BookInfo getBookInfo() {
return bookInfo;
}
public void setBookInfo(BookInfo bookInfo) {
this.bookInfo = bookInfo;
}
public BookService getBookService() {
return bookService;
}
public void setBookService(BookService bookService) {
this.bookService = bookService;
}
/**
* 保存记录
* @return
*/
public String save(){
this.bookService.saveRecord(this.bookInfo);
return SUCCESS;
}
/**
* 更新记录
*/
public String update(){
this.bookService.updateRecord(bookInfo);
return SUCCESS;
}
/**
* 删除一条记录
*/
public String del(){
this.bookService.delRecord(bookInfo);
return SUCCESS;
}
/**
* 删除多条记录
*/
public String delAll(){
this.bookService.delAll(ids);
return SUCCESS;
}
/**
* 查询一条记录
*/
public String showRecord(){
bookInfo = this.bookService.showById(bookInfo.getId());
return SUCCESS;
}
/**
* 显示所有记录
*/
@SuppressWarnings("unchecked")
public String showAllRecord(){
int size=3;
try {
Integer.parseInt(this.getPage()+"");
} catch (Exception e) {
System.out.println("参数错误!");
this.setPage("1");
}
SitePage sitePage = new SitePage();
sitePage.setCurrentPage(Integer.parseInt(this.getPage()+""));
sitePage.setPageSize(3);
sitePage.setPageUrl("showBook");
sitePage.setRecordCount(this.bookService.getBookCount());
try {
ServletActionContext.getRequest().setAttribute("bookpage", sitePage.getPage());
} catch (Exception e) {
e.printStackTrace();
}
Map request = (Map) ActionContext.getContext().get("request");
request.put("list", this.bookService.showAll(Integer.parseInt(this.getPage()+""),size));
return SUCCESS;
}
}
9. 表现控制
<?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>
<constant name="struts.devMode" value="true" />
<package name="default" extends="struts-default">
<action name="showBook" class="com.web.action.BookAction" method="showAllRecord">
<result>show.jsp</result>
</action>
<action name="saveBook" class="com.web.action.BookAction" method="save">
<result name="success" type="redirect">showBook</result>
<result name="input">index.jsp</result>
</action>
<action name="delBook" class="com.web.action.BookAction" method="del">
<result name="success" type="redirect">showBook</result>
</action>
<action name="delAllBook" class="com.web.action.BookAction" method="delAll">
<result name="success" type="redirect">showBook</result>
</action>
<action name="saveUpdate" class="com.web.action.BookAction" method="update">
<result name="success" type="redirect">showBook</result>
</action>
<action name="updateBook" class="com.web.action.BookAction" method="showRecord">
<result>update.jsp</result>
</action>
</package>
</struts>
常用配置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">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myweb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">你的密码</property>
<property name="hibernate.proxool.pool_alias">DBPool</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.transaction.JDBCTransactionFactory">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="connection.autocommit">true</property>
<property name="hibernate.hbm2ddl.auto">none</property>
<mapping resource="com/web/bean/BookInfo.hbm.xml" />
</session-factory>
</hibernate-configuration>
配置WebRoot/WEB-INF/applicationContext.xml
<?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/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 声明一个Hibernate 3 的事物管理器供代理类自动管理事务用 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
<bean id="bookDAO" class="com.web.dao.impl.BookDAOImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="bookService" class="com.web.service.impl.BookServiceImpl">
<property name="bookDAO" ref="bookDAO"></property>
</bean>
<bean id="bookAction" class="com.web.action.BookAction">
<property name="bookService" ref="bookService"></property>
</bean>
<!--<bean id="SaveBookAction" class="com.web.action.BookAction">
<property name="bookService" ref="bookService"></property>
</bean>
<bean id="DelBookAction" class="com.web.action.BookAction">
<property name="bookService" ref="bookService"></property>
</bean>-->
</beans>
配置WebRoot/WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>My Web</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
10. 前端 index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>添加记录</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">
</head>
<body>
<center>
<h3>添加记录</h3>
<s:form action="saveBook">
<s:textfield label="书名" name="bookInfo.bookname"></s:textfield>
<s:textfield label="作者" name="bookInfo.author"></s:textfield>
<s:textfield label="价格" name="bookInfo.bookprice"></s:textfield>
<s:textfield label="书号" name="bookInfo.bookid"></s:textfield>
<s:submit value="提交"></s:submit>
</s:form>
</center>
</body>
</html>
10. 前端 show.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>所有记录</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">
<script type="text/javascript">
function CheckAll(thisform){
for (var i=0;i<thisform.elements.length;i++){
var e = thisform.elements[i];
if (e.Name != "chkAll"&&e.disabled!=true)
e.checked = thisform.chkAll.checked;
}
}
</script>
<style type="text/css">
*,html,body {font-size: 12px;}
.td1 {background: #eeeeee;}
.td2 {background: #fefefe;}
.page {
PADDING-RIGHT: 3px; PADDING-LEFT: 3px; PADDING-BOTTOM: 3px; MARGIN: 3px; PADDING-TOP: 3px; TEXT-ALIGN: center
}
.page A {
BORDER-RIGHT: #ddd 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #ddd 1px solid; PADDING-LEFT: 5px; PADDING-BOTTOM: 2px; BORDER-LEFT: #ddd 1px solid; COLOR: #88af3f; MARGIN-RIGHT: 2px; PADDING-TOP: 2px; BORDER-BOTTOM: #ddd 1px solid; TEXT-DECORATION: none
}
.page A:hover {
BORDER-RIGHT: #85bd1e 1px solid; BORDER-TOP: #85bd1e 1px solid; BORDER-LEFT: #85bd1e 1px solid; COLOR: #638425; BORDER-BOTTOM: #85bd1e 1px solid; BACKGROUND-COLOR: #f1ffd6
}
.page A:active {
BORDER-RIGHT: #85bd1e 1px solid; BORDER-TOP: #85bd1e 1px solid; BORDER-LEFT: #85bd1e 1px solid; COLOR: #638425; BORDER-BOTTOM: #85bd1e 1px solid; BACKGROUND-COLOR: #f1ffd6
}
.page SPAN.current {
BORDER-RIGHT: #b2e05d 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #b2e05d 1px solid; PADDING-LEFT: 5px; FONT-WEIGHT: bold; PADDING-BOTTOM: 2px; BORDER-LEFT: #b2e05d 1px solid; COLOR: #fff; MARGIN-RIGHT: 2px; PADDING-TOP: 2px; BORDER-BOTTOM: #b2e05d 1px solid; BACKGROUND-COLOR: #b2e05d
}
.page SPAN.disabled {
BORDER-RIGHT: #f3f3f3 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #f3f3f3 1px solid; PADDING-LEFT: 5px; PADDING-BOTTOM: 2px; BORDER-LEFT: #f3f3f3 1px solid; COLOR: #ccc; MARGIN-RIGHT: 2px; PADDING-TOP: 2px; BORDER-BOTTOM: #f3f3f3 1px solid
}
</style>
</head>
<body>
<center>
<h3>
所有记录
</h3>
</center>
<s:form theme="simple" action="delAllBook" method="post">
<table cellpadding="6" cellspacing="1" bgcolor="#dddddd"
align="center" width="600">
<tr class="td1">
<td align="center">全/否 </td>
<td align="center">序号</td>
<td align="center">书号</td>
<td align="center">书名</td>
<td align="center">价格</td>
<td align="center">作者</td>
<td align="center">操作</td>
</tr>
<s:iterator value="#request.list" id="book" status="b">
<tr class="td2">
<td align="center" width="30">
<s:checkbox name="ids" value="false" fieldValue="%{#book.id}"></s:checkbox>
</td>
<td align="center"><s:property value="#b.index+1"/></td>
<td>${book.bookid}</td>
<td>${book.bookname}</td>
<td>${book.bookprice}</td>
<td>${book.author}</td>
<td align="center"><s:a href="updateBook?bookInfo.id=%{#book.id}">修改</s:a> </td>
</tr>
</s:iterator>
<tr class="td1">
<td align="center"><s:checkbox name="chkAll" οnclick="CheckAll(this.form)"></s:checkbox></td>
<td colspan="6" align="right">
<s:a href="index.jsp">添加</s:a> |
<s:submit value="删除"></s:submit>
</td>
</tr>
</table>
</s:form>
<center><div class="page">${bookpage}</div></center>
</body>
</html>
10. 前端 update.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>修改</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">
</head>
<body>
<center>
<s:form action="saveUpdate">
<s:textfield value="%{bookInfo.bookid}" label="书号" name="bookInfo.bookid"></s:textfield>
<s:textfield value="%{bookInfo.bookname}" label="书名" name="bookInfo.bookname"></s:textfield>
<s:textfield value="%{bookInfo.bookprice}" label="价格" name="bookInfo.bookprice"></s:textfield>
<s:textfield value="%{bookInfo.author}" label="作者" name="bookInfo.author"></s:textfield>
<s:hidden value="%{bookInfo.id}" name="bookInfo.id"></s:hidden>
<s:submit value="修改"></s:submit>
</s:form>
</center>
</body>
</html>
11. 实现