1.使用工具:MyEclipse10、MySql 5.6
工程目录:
所需的jar包:mysql-connector-java-5.1.28-bin
2.数据库底层开发:
/*创建一个存放书籍信息的数据库表,其中书籍信息包括书籍编号、书籍名称、书籍ISBN号以及书籍价格.*/
create table book(
bookId int(11) not null auto_increment,
bookName varchar(30) default null,
bookNo varchar(30) default null,
bookPrice double(5,2) default null,
primary key(bookId)
);
3.持久层开发:
持久层开发主要包含两部分:
(1).Hibernate配置
package hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
private static ServiceRegistry serviceRegistry;
static {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* 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();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} 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 hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
HibernateSessionFactory类是配置hibernate框架时,软件自动生成的。
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">chen2014</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="myeclipse.connection.profile">com.mysql.jdbc.Driver</property>
<!-- 添加的对象关系映射文件 -->
<mapping resource="po/Book.hbm.xml" />
</session-factory>
</hibernate-configuration>
hibernate.cfg.xml
(2).实体类和映射文件的开发.
/*创建一个Book实体类*/
package po;
public class Book {
private int bookId; //书籍编号
private String bookName; //书籍名称
private String bookNo; //书籍ISBN号
private double bookPrice; //书籍价格
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookNo() {
return bookNo;
}
public void setBookNo(String bookNo) {
this.bookNo = bookNo;
}
public double getBookPrice() {
return bookPrice;
}
public void setBookPrice(double bookPrice) {
this.bookPrice = bookPrice;
}
}
实体类Book.java
<?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="po.Book" table="book">
<id name="bookId"> <!-- 配置标识 -->
<generator class="identity"></generator> <!-- 配置生成策略 -->
</id>
<property name="bookName"></property> <!-- 配置bookName属性 -->
<property name="bookNo"></property> <!-- 配置bookNo属性 -->
<property name="bookPrice"></property> <!-- 配置bookPrice属性 -->
</class>
</hibernate-mapping>
配置文件 Book.hbm.xml
4.数据访问层的开发
数据访问层又称为DAO层,包括3个组成部分:DAO接口、DAO实现类、DAO工厂类。
(1).定义一个DAO接口BookDAO,在该接口中有3个操作数据库的方法:
package dao;
import java.util.List;
import po.Book;
public interface BookDAO {
public void saveBook(Book book); //添加书籍
public Book findByBookNo(String bookNo); //根据ISBN号查询书籍
public List<Book> findAllBook(); //查询所有书籍
}
BookDAO.java
(2).添加DAO接口的实现类BookDAOImpl,在该类中实现BookDAO中声明的方法。
package dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import hibernate.HibernateSessionFactory;
import po.Book;
public class BookDAOImpl implements BookDAO{
public List<Book> findAllBook() {
Session session = HibernateSessionFactory.getSession();//获得Session对象
String hql = "from Book"; //查询所有的书籍
Query query = session.createQuery(hql); //通过HQL创建一个Query对象
List<Book> books = query.list(); //查询所有的记录
HibernateSessionFactory.closeSession(); //关闭Session
return books;
}
public Book findByBookNo(String bookNo) {
Session session = HibernateSessionFactory.getSession();//获得Session对象
String hql = "from Book as book " +
"where book.bookNo = :bookNo"; //根据ISBN号查询书籍
Query query = session.createQuery(hql); //通过HQL创建一个Query对象
query.setString("bookNo", bookNo);
List<Book> books = query.list(); //查询所有的记录
HibernateSessionFactory.closeSession(); //关闭Session
if(books.size() > 0) {
return books.get(0);
}else {
return null;
}
}
public void saveBook(Book book) {
Session session = HibernateSessionFactory.getSession();//获得Session对象
Transaction transaction = session.beginTransaction(); //开启事务
session.save(book); //保存书籍
transaction.commit(); //提交事务
HibernateSessionFactory.closeSession(); //关闭Session
}
}
BookDAOImpl.java
(3).DAO的工厂类,通过调用该工厂类的一个静态方法,能返回一个DAO接口类型的DAO实现类实例对象。
package dao;
public class BookDAOFactory {
public static BookDAO getBookDAOInstance(){
return new BookDAOImpl();
}
}
BookDAOFactory.java
注意:数据访问层是不包含任何业务逻辑的,所以在包含书籍时并不会查询该书籍是否存在。
5.业务逻辑层开发
业务逻辑的开发和数据访问层基本类似。
(1)定义业务逻辑组件接口
package service;
import java.util.List;
import po.Book;
public interface BookService {
public boolean inputBook(Book book);//录入书籍
public List<Book> showAllBook(); //显示所有书籍
}
BookService.java
(2)添加业务逻辑组件实现类
package service;
import java.util.List;
import dao.BookDAO;
import dao.BookDAOFactory;
import po.Book;
public class BookServiceImpl implements BookService{
private BookDAO bookDAO =
BookDAOFactory.getBookDAOInstance();
public boolean inputBook(Book book) {
Book oldBook = bookDAO.
findByBookNo(book.getBookNo());
if(oldBook != null) {
return false;
}else {
bookDAO.saveBook(book);
return true;
}
}
public List<Book> showAllBook() {
return bookDAO.findAllBook();
}
}
BookServiceImpl.java
(3).添加业务逻辑组件工厂类
package service;
public class BookServiceFactory {
public static BookService getBookServiceInstance(){
return new BookServiceImpl();
}
}
BookServiceFactory.java
6.表现层开发
(1)书籍录入
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<center>
<form action="bookInput.action" method="post">
<table>
<tr><td colspan="2">录入图书</td></tr>
<tr><td colspan="2"><s:actionmessage/></td></tr>
<tr>
<td>书籍名称:</td>
<td><input type="text" name="bookName"/></td>
</tr>
<tr>
<td>书籍ISBN号:</td>
<td><input type="text" name="bookNo"/></td>
</tr>
<tr>
<td>书籍价格:</td>
<td><input type="text" name="bookPrice"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="录入" />
<input type="reset" value="重置" />
<a href="showAllBook.action">查询所有图书</a>
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
bookInput.jsp
package action;
import com.opensymphony.xwork2.ActionSupport;
import po.Book;
import service.BookService;
import service.BookServiceFactory;
public class BookInputAction extends ActionSupport {
private String bookName; //书籍名称
private String bookNo; //书籍ISBN号
private double bookPrice; //书籍价格
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookNo() {
return bookNo;
}
public void setBookNo(String bookNo) {
this.bookNo = bookNo;
}
public double getBookPrice() {
return bookPrice;
}
public void setBookPrice(double bookPrice) {
this.bookPrice = bookPrice;
}
public String execute() throws Exception {
Book book = new Book(); //创建一个Book类实例对象
book.setBookName(bookName); //设置书籍名称
book.setBookNo(bookNo); //设置书籍ISBN号
book.setBookPrice(bookPrice); //设置书籍价格
BookService bookService =
BookServiceFactory.getBookServiceInstance();//获得业务逻辑组件实例
if(bookService.inputBook(book)) { //完成书籍录入,并判断是否录入成功
this.addActionMessage("录入图书成功!");//录入成功
return SUCCESS;
}else {
this.addActionMessage("录入图书失败!");//录入失败
return INPUT;
}
}
}
BookInputAction.java
(2). 书籍的显示
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<center>
<h1>查看所有书籍列表</h1>
<table border="1">
<tr>
<td>书籍编号</td>
<td>书籍名称</td>
<td>书籍ISBN号</td>
<td>书籍价格</td>
</tr>
<s:iterator value="#request.bookList" var="book"> <!--遍历循环-->
<tr>
<td><s:property value="#book.bookId"/></td> <!--输出书籍编号-->
<td><s:property value="#book.bookName"/></td> <!--输出书籍名称-->
<td><s:property value="#book.bookNo"/></td> <!--输出书籍ISBN号-->
<td><s:property value="#book.bookPrice"/></td> <!--输出书籍价格-->
</tr>
</s:iterator>
</table>
</center>
</body>
</html>
showAllBook.jsp
package action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import po.Book;
import service.BookService;
import service.BookServiceFactory;
public class ShowAllBookAction extends ActionSupport {
public String execute() throws Exception {
BookService bookService =
BookServiceFactory.getBookServiceInstance();//获得业务逻辑组件实例
List<Book> bookList = bookService.showAllBook();//查询所有书籍
HttpServletRequest request =
ServletActionContext.getRequest(); //获得request对象
request.setAttribute("bookList", bookList); //将图书列表保存到request范围
return SUCCESS;
}
}
ShowAllBook.java
7.其它配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
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_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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></web-app>
web.xml
<?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>
<constant name="struts.i18n.encoding" value="gb2312"></constant>
<package name="struts2" extends="struts-default">
<action name="bookInput" class="action.BookInputAction">
<result name="success">/bookInput.jsp</result>
<result name="input">/bookInput.jsp</result>
</action>
<action name="showAllBook" class="action.ShowAllBookAction">
<result name="success">/showAllBook.jsp</result>
</action>
</package>
</struts>
struts.xml
运行程序,打开浏览器,在地址栏中输入 http://localhost:8080/S2H/bookInput.jsp .