一 序言
鉴于目前J2EE的火热程度,SSH2是每个学生毕业前都必须掌握的一门技术,所以在这里我就使用SSH2技术做一个小型项目,和大家一起学习。
SSH2技术的基础概论就不再提了,直接说特点吧。
1)编程简单,使用SSH2技术使得JAVA代码的编程变得异常简单,几个模块一划分,功能不言自明。
2)控制逻辑有所优化,这里说有所优化是指对比severlet来讲,在SSH2项目编写过程中,关于XML的配置文件还是比较复杂的。
3)界面编写繁琐,其实这不是SSH2负责的领域了,但是作为一个系统必须有MVC,其中的V不可逾越,因此我们尽量多关注MV,JSP页面的编程了解即可。
应大家要求,现提供源码下载,仅作参考:源码下载
二 系统分析
作为一个项目,完成一定的功能即可,过多的追究冷门细节意义不大。因此,项目中使用的SSH2都是基本功能,我的学习过程全靠百度,这里简单说一下SSH2各部门的作用。
Struts2负责控制业务逻辑,即怎么跳转页面,功能怎么组装。
Hibernate负责将对象与数据库关系映射,使我们可以使用面向对象的方法访问数据库。
Spring负责IoC与AOP,属于大管家级别,贯穿整个项目。即管理所有对象的生成和负责事务管理。
三 JAVA代码
首先,我们将代码分包,dao,action,entity,filter,interceptor,一般项目都这样分包,当然还可以细分,比如增加service包。
3.1 entity包
实体类包,即存放所有的实体类。JAVA操作的基本单位是对象,实体即我们项目中需要操作的对象的类,这些类可以说是项目的基本组成单位。作为基本组成单位肯定要和数据库打交道,因此每个类需要配置XML来对数据库映射,映射即Hibernate的功能,映射完成后我们可以直接操作对象来与数据库打交道。
3.1.1 Book
我们网上书店肯定首先是书的定义public class Book implements java.io.Serializable { private Integer bookId;//私有化Field,ID,书名,作者等
private String bookNumber;
private String bookName;
private String bookAuthor;
private String bookPress;
private String bookPicture;
private Integer bookAmount;
private Type type;//这个很重要,这里涉及数据库关联,一本书只有一个类型,一个类型有很多本书,多对一关系many-to-one
private Timestamp bookShelveTime;
private Double bookPrice;
private String bookRemark;
private Integer bookSales;
private Double bookNewPrice; public Book() {//由于我们写了自己的构造器,所以还要写一个空构造器
} public Book(String bookNumber, String bookName, String bookAuthor,//自定义构造器,带参数
String bookPress, String bookPicture, Integer bookAmount,
Type type, Timestamp bookShelveTime, Double bookPrice,
Integer bookSales) {
this.bookNumber = bookNumber;
this.bookName = bookName;
this.bookAuthor = bookAuthor;
this.bookPress = bookPress;
this.bookPicture = bookPicture;
this.bookAmount = bookAmount;
this.type = type;
this.bookShelveTime = bookShelveTime;
this.bookPrice = bookPrice;
this.bookSales = bookSales;
} public Book(String bookNumber, String bookName, String bookAuthor,
String bookPress, String bookPicture, Integer bookAmount,
Type type, Timestamp bookShelveTime, Double bookPrice,
String bookRemark, Integer bookSales,Double bookNewPrice) {
this.bookNumber = bookNumber;
this.bookName = bookName;
this.bookAuthor = bookAuthor;
this.bookPress = bookPress;
this.bookPicture = bookPicture;
this.bookAmount = bookAmount;
this.type = type;
this.bookShelveTime = bookShelveTime;
this.bookPrice = bookPrice;
this.bookRemark = bookRemark;
this.bookSales = bookSales;
this.bookNewPrice = bookNewPrice;
}
//为Field属性生成getter setter
...
}entity类直接关系到数据库中,所以这里需要配置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="entity.Book" table="book" catalog="bookstore">
<id name="bookId" type="java.lang.Integer"><!-- 主键为ID -->
<column name="bookId" />
<generator class="native" /><!--跨数据库自增-->
</id>
<many-to-one name="type" class="entity.Type" lazy="false"><!-- 如代码中一样,配置到Type的多对一关系 -->
<column name="typeId" not-null="true" />
</many-to-one>
<property name="bookNumber" type="java.lang.String">
<column name="bookNumber" length="21" not-null="true" />
</property>
<property name="bookName" type="java.lang.String">
<column name="bookName" length="20" not-null="true" />
</property>
<property name="bookAuthor" type="java.lang.String">
<column name="bookAuthor" length="20" not-null="true" />
</property>
<property name="bookPress" type="java.lang.String">
<column name="bookPress" length="20" not-null="true" />
</property>
<property name="bookPicture" type="java.lang.String">
<column name="bookPicture" length="100" not-null="true" />
</property>
<property name="bookAmount" type="java.lang.Integer">
<column name="bookAmount" not-null="true" />
</property>
<property name="bookShelveTime" type="timestamp">
<column name="bookShelveTime" length="14" not-null="true" />
</property>
<property name="bookPrice" type="java.lang.Double">
<column name="bookPrice" precision="10" not-null="true" />
</property>
<property name="bookRemark" type="java.lang.String">
<column name="bookRemark" length="200" />
</property>
<property name="bookSales" type="java.lang.Integer">
<column name="bookSales" not-null="true" />
</property>
</class>
</hibernate-mapping>3.1.2 Type
书里面包含了书的类型,类型定义public class Type implements java.io.Serializable { private Integer typeId;//类型编号,类型名
private String typeName; public Type() {
} public Type(String typeName) {
this.typeName = typeName;
}
//生成setter getter方法
...
}3.1.3 User
接下来肯定是User用户类了public class User implements java.io.Serializable { private Integer userId;
private String userName;
private String userPassword;
private String userEmail;
private String userNickname;
private Sex sex;//性别为多对一关系
private String userAddress;
private String userPhone;
private String userRemark; public User() {
} public User(String userName, String userPassword, String userEmail,
Sex sex) {
this.userName = userName;
this.userPassword = userPassword;
this.userEmail = userEmail;
this.sex = sex;
} public User(String userName, String userPassword, String userEmail,
String userNickname, Sex sex, String userAddress,
String userPhone, String userRemark) {
this.userName = userName;
this.userPassword = userPassword;
this.userEmail = userEmail;
this.userNickname = userNickname;
this.sex = sex;
this.userAddress = userAddress;
this.userPhone = userPhone;
this.userRemark = userRemark;
}
//生成getter setter方法
...
}对User进行映射
<?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="entity.User" table="user" catalog="bookstore">
<id name="userId" type="java.lang.Integer">
<column name="userId" />
<generator class="native" />
</id>
<many-to-one name="sex" class="entity.Sex" lazy="false"><!-- 多对一映射,lazy设置后读取时自动级联读取内容 -->
<column name="sexId" not-null="true" />
</many-to-one>
<property name="userName" type="java.lang.String">
<column name="userName" length="16" not-null="true" />
</property>
<property name="userPassword" type="java.lang.String">
<column name="userPassword" length="12" not-null="true" />
</property>
<property name="userEmail" type="java.lang.String">
<column name="userEmail" length="100" not-null="true" />
</property>
<property name="userNickname" type="java.lang.String">
<column name="userNickname" length="10" />
</property>
<property name="userAddress" type="java.lang.String">
<column name="userAddress" length="200" />
</property>
<property name="userPhone" type="java.lang.String">
<column name="userPhone" length="24" />
</property>
<property name="userRemark" type="java.lang.String">
<column name="userRemark" length="200" />
</property>
</class>
</hibernate-mapping>3.1.4 Sex
程序员看到这个字段可能会小激动一下,请冷静一下,这只是性别的男女而已public class Sex implements java.io.Serializable { private Integer sexId;
private String sexType; public Sex() {
} public Sex(String sexType) {
this.sexType = sexType;
}
//生成setter getter方法
...
}然后生成数据库映射
<?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="entity.Sex" table="sex" catalog="bookstore">
<id name="sexId" type="java.lang.Integer">
<column name="sexId" />
<generator class="native" />
</id>
<property name="sexType" type="java.lang.String">
<column name="sexType" length="4" not-null="true" />
</property>
</class>
</hibernate-mapping>3.1.5 Bargain
作为一个成熟的系统,肯定该出现一些稍微不是特别直观的实体类了,比如折扣,哪本书打折了,现在卖多少钱public class Bargain implements java.io.Serializable { private Integer bargainId;
private Book book;//多对一关系,一本书可以有各种折扣
private Double bookNewPrice; public Bargain() {
} public Bargain(Book book, Double bookNewPrice) {
this.book = book;
this.bookNewPrice = bookNewPrice;
}
//生成getter setter方法
...
}数据库映射
<?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="entity.Bargain" table="bargain" catalog="bookstore">
<id name="bargainId" type="java.lang.Integer">
<column name="bargainId" />
<generator class="native" />
</id>
<many-to-one name="book" class="entity.Book" lazy="false" unique="true"><!-- 多对一配置,可以级联读取,唯一存在 -->
<column name="bookId" not-null="true" />
</many-to-one>
<property name="bookNewPrice" type="java.lang.Double">
<column name="bookNewPrice" precision="10" not-null="true" />
</property>
</class>
</hibernate-mapping>3.1.6 Manager
这时候就该出现管理员了,权限狗,来管理系统public class Manager implements java.io.Serializable { private Integer managerId;
private String managerName;
private String managerPassword; public Manager() {
} public Manager(String managerName, String managerPassword) {
this.managerName = managerName;
this.managerPassword = managerPassword;
}
//生成getter setter方法
...
}数据库映射
<?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="entity.Manager" table="manager" catalog="bookstore">
<id name="managerId" type="java.lang.Integer">
<column name="managerId" />
<generator class="native" />
</id>
<property name="managerName" type="java.lang.String">
<column name="managerName" length="16" not-null="true" />
</property>
<property name="managerPassword" type="java.lang.String">
<column name="managerPassword" length="12" not-null="true" />
</property>
</class>
</hibernate-mapping>3.1.7 Order
订单类,由于订单里面需要出现用户,书,其他信息,所以这里用两张表来表示,使用两个多对一来完成多对多<pre name="code" class="java">public class Orders implements java.io.Serializable { private Integer ordersId;
private String ordersNumber;
private User user;//这是哪个用户的订单,多对一关系
private Timestamp ordersTime;
private String isDeal;
private Double totalMoney; public Orders() {
} public Orders(String ordersNumber,User user, Timestamp ordersTime,String isDeal,Double totalMoney) {
this.ordersNumber = ordersNumber;
this.user = user;
this.ordersTime = ordersTime;
this.isDeal = isDeal;
this.totalMoney = totalMoney;
}
//生成getter setter方法
...
}数据库映射
<?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="entity.Orders" table="orders" catalog="bookstore">
<id name="ordersId" type="java.lang.Integer">
<column name="ordersId" />
<generator class="native" />
</id>
<property name="ordersNumber" type="java.lang.String">
<column name="ordersNumber" length="21" not-null="true" />
</property>
<many-to-one name="user" class="entity.User" lazy="false">
<column name="userId" not-null="true" />
</many-to-one>
<property name="ordersTime" type="timestamp">
<column name="ordersTime" length="19" not-null="true" />
</property>
<property name="isDeal" type="java.lang.String">
<column name="isDeal" length="1" not-null="true" />
</property>
<property name="totalMoney" type="java.lang.Double">
<column name="totalMoney" precision="10" not-null="true" />
</property>
</class>
</hibernate-mapping>3.1.8 Ordersbook
public class Ordersbook implements java.io.Serializable { private Integer ordersBookId;
private Orders orders;//好多书对应一个订单,因此是多对一
private Book book;//好多订单都可以有某一本书,谋一本书可以出现在好多订单中,多对一
private Integer bookAmount; public Ordersbook() {
} public Ordersbook(Orders orders, Book book, Integer bookAmount) {
this.orders = orders;
this.book = book;
this.bookAmount = bookAmount;
}
//生成setter getter方法
...
}数据库映射
<?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="entity.Ordersbook" table="ordersbook" catalog="bookstore">
<id name="ordersBookId" type="java.lang.Integer">
<column name="ordersBookId" />
<generator class="native" />
</id>
<many-to-one name="orders" class="entity.Orders" lazy="false"><!-- 两个多对一代替了多对多 -->
<column name="ordersId" not-null="true" />
</many-to-one>
<many-to-one name="book" class="entity.Book" lazy="false" unique="true">
<column name="bookId" not-null="true" />
</many-to-one>
<property name="bookAmount" type="java.lang.Integer">
<column name="bookAmount" not-null="true" />
</property>
</class>
</hibernate-mapping>3.1.9 Recommended
推荐购书目录,大家都懂public class Recommended implements java.io.Serializable { private Integer recommendedId;
private Book book; public Recommended() {
} public Recommended(Book book) {
this.book = book;
}
//生成getter setter方法
...
}数据库映射
<?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="entity.Recommended" table="recommended" catalog="bookstore">
<id name="recommendedId" type="java.lang.Integer">
<column name="recommendedId" />
<generator class="native" />
</id>
<many-to-one name="book" class="entity.Book" lazy="false" unique="true">
<column name="bookId" not-null="true" />
</many-to-one>
</class>
</hibernate-mapping>至此,所有的实体类结束,实体类种类繁多,但是都很简单,不涉及逻辑,注意数据库关联的时候的多对一的关系即可
3.2 dao包
实体类结束,该管理实体类了。其实这里可以额外分化出service包,即service定义管理方法,dao才去和数据库打交道。比如,我的service定义有一个方法是先存储用户,后存储书,再存储订单,这三个功能是一个方法,dao就可以分别写三个方法,然后再service中组装。这里我们的功能没那么复杂,所以就直接写成dao了。因为在功能简单的情况下,写完service和dao后,你会发现service写的和dao一模一样。3.2.1 BookManager
管理图书的操作,CRUD以及花样CRUDpackage dao; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import java.util.*; import entity.*; public class BookManage extends HibernateDaoSupport { // 添加新的图书
public int addBook(Book book) {
int i = 0;
try {
this.getHibernateTemplate().save(book);//利用hibernate的模板操作,编码简单
i = 1;
} catch (Exception e) {
e.printStackTrace();
}
return i;
}
// 修改图书
public int updateBook(Book book) {
int i = 0;
try {
this.getHibernateTemplate().update(book);
i = 1;
} catch (Exception e) {
e.printStackTrace();
}
return i;
} // 根据图书ID查询该图书
public Book findBook(int bookId) {
try {
Book book = (Book) this.getHibernateTemplate().get("entity.Book",bookId);
return book;
} catch (RuntimeException re) {
throw re;
}
} // 查询销量最好的图书
@SuppressWarnings("unchecked")
public List<Book> bestSellingBook(int pageNumber, int pageSize) {
String hql = "from Book as book where book.bookSales > 0 and book.bookAmount > 0 order by book.bookSales desc ";
try {
List<Book> bestSellingBook = this.getHibernateTemplate().find(hql);
return bestSellingBook;
} catch (RuntimeException re) {
throw re;
}
} // 查询最新上架的图书
@SuppressWarnings("unchecked")
public List<Book> latestBook(int pageNumber, int pageSize) {
String hql = "from Book as book where book.bookAmount > 0 order by book.bookShelveTime desc ";
try {
List<Book> latestBook = this.getHibernateTemplate().find(hql);
return latestBook;
} catch (RuntimeException re) {
throw re;
}
} // 查询推荐图书ID
@SuppressWarnings("unchecked")
public List<Recommended> allRecommended(int pageNumber, int pageSize) {
String hql = "from Recommended as recommended ";
try {
List<Recommended> allRecommended = this.getHibernateTemplate().find(hql);
return allRecommended;
} catch (RuntimeException re) {
throw re;
}
} // 查询特价图书ID
@SuppressWarnings("unchecked")
public List<Bargain> allBargain(int pageNumber, int pageSize) {
String hql = "from Bargain as bargain ";
try {
List<Bargain> allBargain = this.getHibernateTemplate().find(hql);
return allBargain;
} catch (RuntimeException re) {
throw re;
}
} // 根据图书名称查询图书
@SuppressWarnings("unchecked")
public List<Book> allBookByName(String bookName, int pageNumber,
int pageSize) {
String hql = "from Book as book where book.bookName like '%" + bookName + "%'";
try {
this.getHibernateTemplate().setMaxResults(pageSize);
List<Book> allBookByName = this.getHibernateTemplate().find(hql);
return allBookByName;
} catch (RuntimeException re) {
throw re;
}
} // 根据作者查询图书
@SuppressWarnings("unchecked")
public List<Book> allBookByAuthor(String bookAuthor, int pageNumber, int pageSize) {
String hql = "from Book as book where book.bookAuthor like '%" + bookAuthor + "%'";
try {
this.getHibernateTemplate().setMaxResults(pageSize);
List<Book> allBookByAuthor = this.getHibernateTemplate().find(hql);
return allBookByAuthor;
} catch (RuntimeException re) {
throw re;
}
} // 根据出版社查询图书
@SuppressWarnings("unchecked")
public List<Book> allBookByPress(String bookPress, int pageNumber, int pageSize) {
String hql = "from Book as book where book.bookPress like '%" + bookPress + "%'";
try {
this.getHibernateTemplate().setMaxResults(pageSize);
List<Book> allBookByPress = this.getHibernateTemplate().find(hql);
return allBookByPress;
} catch (RuntimeException re) {
throw re;
}
} //根据类别ID来获取类别
public Type findType(int typeId){
try{
Type type = (Type)this.getHibernateTemplate().get("entity.Type", typeId);
return type;
}catch(RuntimeException re){
throw re;
}
} //根据图书类别来查询图书
@SuppressWarnings("unchecked")
public List<Book> allBookByType(int typeId, int pageNumber, int pageSize){
String hql = "from Book as book where book.type.typeId="+typeId;
try{
List<Book> allBookByType= this.getHibernateTemplate().find(hql);
return allBookByType;
}catch(RuntimeException re){
throw re;
}
} //查询图书是否为特价图书
@SuppressWarnings("unchecked")
public Bargain isBargain(int bookId){
Bargain bargain = null;
String hql = "from Bargain as bargain where bargain.book.bookId="+bookId;
try{
List<Bargain> bargainList = this.getHibernateTemplate().find(hql);
if(bargainList.size() > 0){
bargain = bargainList.get(0);
}
}catch(RuntimeException re){
throw re;
}
return bargain;
}
}3.2.2 OrdersManager
处理和订单相关的操作package dao; 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 java.sql.SQLException;
import java.util.*;
import entity.*; public class OrdersManage extends HibernateDaoSupport{ //查询所有订单
@SuppressWarnings("unchecked")
public List<Orders> allOrders(final int pageNumber,final int pageSize){
List<Orders> allOrders = getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
String hql = "from Orders as orders order by ordersTime desc";
Query query = session.createQuery(hql);
query.setFirstResult((pageNumber-1)*pageSize);
query.setMaxResults(pageSize);
List<Orders> list = query.list();
return list;
}
});
return allOrders;
} //查询所有订单
@SuppressWarnings("unchecked")
public List<Orders> allOrdersByDeal(final String isDeal,final int pageNumber,final int pageSize){
List<Orders> allOrders = getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
String hql = "from Orders as orders where orders.isDeal = '"+isDeal+"' order by ordersTime desc";
Query query = session.createQuery(hql);
query.setFirstResult((pageNumber-1)*pageSize);
query.setMaxResults(pageSize);
List<Orders> list = query.list();
return list;
}
});
return allOrders;
} //添加一个新的订单
@SuppressWarnings("unchecked")
public int addOrders(Orders orders){
int i = 0;
try{
this.getHibernateTemplate().save(orders);
String hql = "select max(ordersId) from Orders";
List<Integer> idList = this.getHibernateTemplate().find(hql);
if(idList.size()>0){
i = idList.get(0);
}
}catch (RuntimeException re) {
throw re;
}
return i ;
} //删除一个订单
public int deleteOrders(int ordersId){
int i = 0;
try{
this.getHibernateTemplate().delete(this.getHibernateTemplate().get("entity.Orders", ordersId));
i = 1;
}catch(RuntimeException re){
throw re;
}
return i ;
} //修改订单
public void updateOrders(Orders orders){
try{
this.getHibernateTemplate().update(orders);
}catch(RuntimeException re){
throw re;
}
} //根据ID查询订单
public Orders findOrders(int ordersId){
try{
Orders orders = (Orders)this.getHibernateTemplate().get("entity.Orders", ordersId);
return orders;
}catch(RuntimeException re){
throw re;
}
} //添加一条订单图书信息
public void addOrdersbook(Ordersbook ordersbook){
try{
this.getHibernateTemplate().save(ordersbook);
}catch (RuntimeException re) {
throw re;
}
} //根据userId获取该用户所有订单
@SuppressWarnings("unchecked")
public List<Orders> allOrdersByUser(int userId,int pageNumber,int pageSize){
String hql = "from Orders as orders where orders.user.userId="+userId+" order by ordersTime desc";
try{
List<Orders> allOrdersByUser = this.getHibernateTemplate().find(hql);
return allOrdersByUser;
}catch(RuntimeException re){
throw re;
}
}
//根据userId,订单处理状态获取该用户所有订单
@SuppressWarnings("unchecked")
public List<Orders> allOrdersByUserDeal(int userId,String isDeal,int pageNumber,int pageSize){
String hql = "from Orders as orders where orders.user.userId="+userId+" and orders.isDeal='"+isDeal+"' order by ordersTime desc";
try{
List<Orders> allOrdersByUser = this.getHibernateTemplate().find(hql);
return allOrdersByUser;
}catch(RuntimeException re){
throw re;
}
} //根据ordersId获取该订单所有订单图书
@SuppressWarnings("unchecked")
public List<Ordersbook> allOrdersbookByOrders(int ordersId){
String hql = "from Ordersbook as ordersbook where ordersbook.orders.ordersId="+ordersId;
try{
List<Ordersbook> allOrdersbookByOrders = this.getHibernateTemplate().find(hql);
return allOrdersbookByOrders;
}catch(RuntimeException re){
throw re;
}
} }3.2.3 PersonManager
对人的操作,包括用户与管理员package dao; import java.util.*; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import entity.*; public class PersonManage extends HibernateDaoSupport { //管理员登录验证
@SuppressWarnings("unchecked")
public boolean checkManager(String managerName,String managerPassword){
boolean flag = false;
String hql = "from Manager as manager where manager.managerName = '"+managerName+"' and manager.managerPassword = '"+managerPassword+"'";
List<Manager> managerList = this.getHibernateTemplate().find(hql);
if(managerList.size()>0){
flag = true;
}
return flag;
} //获取用户信息
public User findUser(int userId){
try{
User user = (User)this.getHibernateTemplate().get("entity.User", userId);
return user;
}catch(RuntimeException re){
throw re;
}
} //普通用户登录验证
@SuppressWarnings("unchecked")
public User checkUser(String userName,String userPassword){
String hql = "from User as user where user.userName = '"+userName+"' and user.userPassword = '"+userPassword+"'";
User user = null;
try{
List<User> userList = this.getHibernateTemplate().find(hql);
if(userList.size() > 0){
user = new User();
user = userList.get(0);
}
}catch(RuntimeException re){
throw re;
}
return user;
}
//检查注册用户名是否已经存在
@SuppressWarnings("unchecked")
public boolean isUserNameExist(String userName){
boolean flag = true;
String hql = "from User as user where user.userName = '"+userName+"'";
try{
List<User> userList= this.getHibernateTemplate().find(hql);
if(userList.size() == 0){
flag = false;
}
return flag;
}catch (RuntimeException re) {
throw re;
}
}
//添加一条用户信息
public int addUser(User user){
int i = 0;
try{
this.getHibernateTemplate().save(user);
i = 1;
}catch(RuntimeException re){
throw re;
}
return i ;
}
//修改一条用户信息
public int updateUserInfor(User user){
int i = 0;
try{
this.getHibernateTemplate().update(user);
i = 1;
}catch (RuntimeException re) {
throw re;
}
return i;
}
//根据sexId查询Sex
public Sex findSex(int sexId){
try{
Sex sex = (Sex)this.getHibernateTemplate().get("entity.Sex", sexId);
return sex;
}catch (RuntimeException re) {
throw re;
}
}
}至此,常见的操作已经结束。
可能大家会觉得操作功能很乱,没有很清晰的逻辑,那是因为大家没有从做这个系统的需求分析,有了需求分析以后需要什么功能都一目了然,编写起来就不乱了。3.3 action包
这是最烦的一个包,之前实现了各种功能。但是都是基础功能,这些功能还没有去组装起来。这里的Action完全支撑了JSP页面中的每一个按钮。所以这里需要有那个Action其实也是需求分析里面分析过了的,页面有什么按钮,这里就有什么Action。下面类名很清晰,基本不用什么解释3.3.1 AllBookAction
获取推荐书、新书、特价书,这些可以作为全局变量看待,因为总是在JSP中显示。package com.huizhi.action; import com.opensymphony.xwork2.ActionSupport; import java.util.*; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import dao.BookManage;
import entity.*; @SuppressWarnings("serial")
public class AllBookAction extends ActionSupport{ private BookManage bookManage;
//Spring注入bookManage
public void setBookManage(BookManage bookManage) {
this.bookManage = bookManage;
} public String execute(){
//推荐书
List<Recommended> allRecommended = bookManage.allRecommended(1, 6);
List<Book> recommendedBook = new ArrayList<Book>();
for(Recommended recommended : allRecommended){
Book book = new Book();
book = recommended.getBook();
recommendedBook.add(book);
}
//特价书
List<Bargain> allBargain = bookManage.allBargain(1, 6);
List<Book> bargainBook = new ArrayList<Book>();
for(Bargain bargain : allBargain){
Book book = new Book();
book = bargain.getBook();
bargainBook.add(book);
}
//新书
List<Book> latestBook = bookManage.latestBook(1, 6); HttpServletRequest request = ServletActionContext.getRequest();
request.setAttribute("recommendedBook", recommendedBook);
request.setAttribute("bargainBook", bargainBook);
request.setAttribute("latestBook", latestBook); return null;
} }3.3.2 AllOrderAction
获得所有订单信息package com.huizhi.action; import com.opensymphony.xwork2.ActionSupport; import dao.*;
import java.util.*;
import entity.*; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; @SuppressWarnings("serial")
public class AllOrdersAction extends ActionSupport{ private OrdersManage ordersManage;
//Spring注入
public void setOrdersManage(OrdersManage ordersManage) {
this.ordersManage = ordersManage;
}
public String execute(){
HttpServletRequest request = ServletActionContext.getRequest();
List<Orders> allOrders = new ArrayList<Orders>();
String pageNumberString = request.getParameter("pageNumber");
if(pageNumberString == null || "".equals(pageNumberString.trim())){
pageNumberString = "1";
}
int pageNumber = Integer.parseInt(pageNumberString);
pageNumber = 1;
int pageSize = 10;
String searchType = request.getParameter("searchType");
if(searchType == null || "".equals(searchType.trim())){
searchType = "all";
}
if("all".equals(searchType)){
allOrders = ordersManage.allOrders(pageNumber, pageSize);
}
if("isDeal".equals(searchType)){
allOrders = ordersManage.allOrdersByDeal("1", pageNumber, pageSize);
}
if("isNotDeal".equals(searchType)){
allOrders = ordersManage.allOrdersByDeal("0", pageNumber, pageSize);
}
int sequence = (pageNumber-1)*pageSize;
request.setAttribute("allOrders", allOrders);
request.setAttribute("sequence", sequence);
return null;
}
}3.3.3 BookAction
package com.huizhi.action; import java.io.File;
import java.sql.Timestamp;
import java.text.*;
import java.util.*;
import java.util.Date; import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import dao.BookManage;
import entity.*; @SuppressWarnings("serial")
public class BookAction extends ActionSupport{ private String bookName;
private String bookAuthor;
private String bookPress;
private String bookRemark;
private int typeId;
private int bookAmount;
private double bookPrice;
private BookManage bookManage; private File doc;
private String fileName;
private String contentType;
private String dir;
private String targetFileName; public void setDoc(File file) {
this.doc = file;
} public void setDocFileName(String fileName) {
this.fileName = fileName;
}
public void setDocContentType(String contentType) {
this.contentType = contentType;
} public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getTargetFileName() {
return targetFileName;
}
public void setTargetFileName(String targetFileName) {
this.targetFileName = targetFileName;
}
private String generateFileName(String fileName){
DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
String formatDate = format.format(new Date());
int random = new Random().nextInt(100000);
int position = fileName.lastIndexOf(".");
String extension = fileName.substring(position);
return formatDate+random+extension;
} public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookAuthor() {
return bookAuthor;
}
public void setBookAuthor(String bookAuthor) {
this.bookAuthor = bookAuthor;
}
public String getBookPress() {
return bookPress;
}
public void setBookPress(String bookPress) {
this.bookPress = bookPress;
}
public String getBookRemark() {
return bookRemark;
}
public void setBookRemark(String bookRemark) {
this.bookRemark = bookRemark;
}
public int getTypeId() {
return typeId;
}
public void setTypeId(int typeId) {
this.typeId = typeId;
}
public int getBookAmount() {
return bookAmount;
}
public void setBookAmount(int bookAmount) {
this.bookAmount = bookAmount;
}
public double getBookPrice() {
return bookPrice;
}
public void setBookPrice(double bookPrice) {
this.bookPrice = bookPrice;
}
public void setBookManage(BookManage bookManage) {
this.bookManage = bookManage;
}
@SuppressWarnings("deprecation")
public String execute(){
String page = "success";
String realPath = ServletActionContext.getRequest().getRealPath("/upload");
String targetDirectory = realPath;
targetFileName =generateFileName(fileName);
setDir(targetDirectory+"\\"+targetFileName);
File target = new File(targetDirectory,targetFileName);
try {
FileUtils.copyFile(doc, target);
} catch (Exception e) {
e.printStackTrace();
}
Book book = new Book();
book.setBookName(bookName);
book.setBookAuthor(bookAuthor);
book.setBookPress(bookPress);
book.setBookPicture(targetFileName);//图片地址
book.setBookRemark(bookRemark);
book.setBookPrice(bookPrice);
book.setBookAmount(bookAmount);
Type type = bookManage.findType(typeId);
book.setType(type);//类别
book.setBookSales(0); String bookNumber = "TSBH";
DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
String formatDate = format.format(new Date());
int random = new Random().nextInt(100000);
bookNumber += formatDate + random; book.setBookNumber(bookNumber);
book.setBookShelveTime(new Timestamp(new Date().getTime()));
bookManage.addBook(book);
return page;
}
}3.3.4 DealOrdersAction
package com.huizhi.action; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import dao.OrdersManage;
import entity.Orders; @SuppressWarnings("serial")
public class DealOrdersAction extends ActionSupport{ private OrdersManage ordersManage; public void setOrdersManage(OrdersManage ordersManage) {
this.ordersManage = ordersManage;
} public String execute(){
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
String ordersIdString = request.getParameter("ordersId");
int ordersId = Integer.parseInt(ordersIdString);
Orders orders = ordersManage.findOrders(ordersId);
orders.setIsDeal("1");
ordersManage.updateOrders(orders);
try {
response.sendRedirect("../manage/manageAllOrders.jsp?searchType=all");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}3.3.5 EnrollAction
package com.huizhi.action; import java.util.regex.Pattern; import com.opensymphony.xwork2.ActionSupport; import dao.PersonManage;
import entity.*; @SuppressWarnings("serial")
public class EnrollAction extends ActionSupport{ private String userName;
private String userPassword;
private String userRePassword;
private String userEmail;
private PersonManage personManage;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getUserRePassword() {
return userRePassword;
}
public void setUserRePassword(String userRePassword) {
this.userRePassword = userRePassword;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public void setPersonManage(PersonManage personManage) {
this.personManage = personManage;
} public String execute(){
User newUser = new User();
newUser.setUserName(userName);
newUser.setUserPassword(userPassword);
newUser.setUserEmail(userEmail);
Sex sex = personManage.findSex(3);
newUser.setSex(sex);
personManage.addUser(newUser);
return "success";
}
public void validate(){
if(!Pattern.matches("[a-zA-Z][a-zA-Z0-9]{5,15}", userName)){
addFieldError("userName", "用户名请使用6-16位英文字母或数字,且以字母开头!");
}
if(!Pattern.matches("[a-zA-Z0-9]{6,12}", userPassword)){
addFieldError("userPassword", "密码请使用6-12位英文字母或数字!");
}
if(!userRePassword.equals(userPassword)){
addFieldError("userRePassword", "两次密码不一致!");
}
if("".equals(userEmail.trim())){
addFieldError("userEmail", "邮箱不能为空!");
}
boolean flag = true;
flag = personManage.isUserNameExist(userName);
if(flag){
addFieldError("userName", "用户名已经存在!");
}
}
}3.3.5 LeftAction
package com.huizhi.action; import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport; import java.util.*; import dao.BookManage;
import entity.*; @SuppressWarnings("serial")
public class LeftAction extends ActionSupport{
private BookManage bookManage;
public void setBookManage(BookManage bookManage) {
this.bookManage = bookManage;
}
public String execute(){
//销量排行榜
List<Book> bestSellingBook = bookManage.bestSellingBook(1, 10);
HttpServletRequest request = ServletActionContext.getRequest();
request.setAttribute("bestSellingBook", bestSellingBook);
return null;
}
}3.3.6 LoginAction
package com.huizhi.action; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport; import dao.PersonManage;
import entity.User; @SuppressWarnings("serial")
public class LoginAction extends ActionSupport{ private String userName;
private String userPassword;
private PersonManage personManage;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public void setPersonManage(PersonManage personManage) {
this.personManage = personManage;
} //普通用户登录
public String loginCheck(){
String page = "fail";
User user = new User();
user = personManage.checkUser(userName, userPassword);
if(user != null){
page = "success";
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = request.getSession();
if(session.getAttribute("loginUser") != null){
session.removeAttribute("loginUser");
}
session.setAttribute("loginUser", user);
}
return page;
}
//管理员登录
public String managerLoginCheck(){
String page = "fail";
boolean flag = false;
flag = personManage.checkManager(userName, userPassword);
if(flag){
page = "success";
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = request.getSession();
if(session.getAttribute("managerLoginName") != null){
session.removeAttribute("managerLoginName");
}
session.setAttribute("managerLoginName", userName);
}
return page;
}
}3.3.7 OneTypeAction
package com.huizhi.action; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport; import java.util.*;
import dao.*;
import entity.*; @SuppressWarnings("serial")
public class OneTypeAction extends ActionSupport{ private BookManage bookManage;
public void setBookManage(BookManage bookManage) {
this.bookManage = bookManage;
} public String execute(){
String page = "oneType";
List<Book> bookList = new ArrayList<Book>();
String typeDescribe = "";
HttpServletRequest request = ServletActionContext.getRequest();
String searchType = request.getParameter("searchType");
String searchDescribe = request.getParameter("searchDescribe"); if(searchType == null || "".equals(searchType.trim())){
page = "error";
}
else {
if(searchDescribe == null || "".equals(searchDescribe.trim())){
page = "error";
}else{
if("bookName".equals(searchType)){//按图书名称
bookList = bookManage.allBookByName(searchDescribe, 1, 10);
typeDescribe = searchDescribe;
}
else if("bookAuthor".equals(searchType)){//按作者名称
bookList = bookManage.allBookByAuthor(searchDescribe, 1, 10);
typeDescribe = searchDescribe;
}
else if("bookPress".equals(searchType)){//按出版社
bookList = bookManage.allBookByPress(searchDescribe, 1, 10);
typeDescribe = searchDescribe;
}
else if("bookType".equals(searchType)){//按书本类别
int typeId = Integer.parseInt(searchDescribe);
Type type = bookManage.findType(typeId);
bookList = bookManage.allBookByType(typeId, 1, 10);
typeDescribe = type.getTypeName();
}
else if("bookStatus".equals(searchType)){//按书本现状,指特价、畅销、最新、推荐
if("bestSelling".equals(searchDescribe)){
//畅销书
typeDescribe = "畅销图书";
bookList = bookManage.bestSellingBook(1, 10);
}
else if("latest".equals(searchDescribe)){
//最新书
typeDescribe = "最新图书";
bookList = bookManage.latestBook(1, 10);
}
else if("recommended".equals(searchDescribe)){
//推荐书
typeDescribe = "推荐图书";
List<Recommended> allRecommended = bookManage.allRecommended(1, 6);
for(Recommended recommended : allRecommended){
Book book = new Book();
book = recommended.getBook();
bookList.add(book);
}
}
else if("bargain".equals(searchDescribe)){
//特价书
typeDescribe = "特价图书";
List<Bargain> allBargain = bookManage.allBargain(1, 6);
for(Bargain bargain : allBargain){
Book book = new Book();
book = bargain.getBook();
bookList.add(book);
}
}else{
page = "error";
}
}else{
page = "error";
}
}
}
request.setAttribute("typeDescribe", typeDescribe);
request.setAttribute("bookList", bookList);
return page;
} }3.3.8 OrdersAction
package com.huizhi.action; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport; import dao.*;
import entity.*;
import java.util.*; @SuppressWarnings("serial")
public class OrdersAction extends ActionSupport{ private OrdersManage ordersManage; public void setOrdersManage(OrdersManage ordersManage) {
this.ordersManage = ordersManage;
} public String execute(){
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = request.getSession();
User user = (User)session.getAttribute("loginUser");
List<Orders> allOrdersByUser = new ArrayList<Orders>();
String searchType = request.getParameter("searchType");
if(searchType == null || "".equals(searchType.trim())){
searchType = "all";
}
if("all".equals(searchType)){
allOrdersByUser = ordersManage.allOrdersByUser(user.getUserId(), 1, 5);
}
if("isDeal".equals(searchType)){
allOrdersByUser = ordersManage.allOrdersByUserDeal(user.getUserId(), "1", 1, 5);
}
if("isNotDeal".equals(searchType)){
allOrdersByUser = ordersManage.allOrdersByUserDeal(user.getUserId(), "0", 1, 5);
}
request.setAttribute("allOrdersByUser", allOrdersByUser);
int sequence = (1-1)*5;
request.setAttribute("sequence", sequence);
return null;
}
}3.3.9 OrdersManageAction
package com.huizhi.action; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport; import dao.*;
import entity.*; import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*; @SuppressWarnings("serial")
public class OrdersManageAction extends ActionSupport{ private OrdersManage ordersManage;
public void setOrdersManage(OrdersManage ordersManage) {
this.ordersManage = ordersManage;
} @SuppressWarnings("unchecked")
public String execute(){ HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = request.getSession(); String updateType = request.getParameter("updateType");
if("add".equals(updateType)){ List<Book> shoppingBook = (List)session.getAttribute("shoppingBook");
double totalMoney = (Double)session.getAttribute("totalMoney");
User user = (User)session.getAttribute("loginUser");
Orders orders = new Orders();
orders.setUser(user);
orders.setOrdersTime(new Timestamp(new Date().getTime()));
orders.setIsDeal("0");
orders.setTotalMoney(totalMoney);
String ordersNumber = "DDBH";
DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
String formatDate = format.format(new Date());
int random = new Random().nextInt(100000);
ordersNumber += formatDate+random; orders.setOrdersNumber(ordersNumber);
int ordersId = ordersManage.addOrders(orders);
Orders newOrders = ordersManage.findOrders(ordersId);
for(Book book : shoppingBook){
Ordersbook ordersbook = new Ordersbook();
ordersbook.setBook(book);
ordersbook.setBookAmount(book.getBookAmount());
ordersbook.setOrders(newOrders);
ordersManage.addOrdersbook(ordersbook);
}
session.removeAttribute("shoppingBook");
session.removeAttribute("totalMoney");
return "success";
}
if("delete".equals(updateType)){
String ordersId = request.getParameter("ordersId");
int i = 0;
i = ordersManage.deleteOrders(Integer.parseInt(ordersId));
if(i == 0){
return "error";
}else{
return "success";
}
}
return null;
}
}3.3.10 ShoppingCartAction
package com.huizhi.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import java.util.*;
import entity.*;
import dao.*;
@SuppressWarnings("serial")
public class ShoppingCartAction extends ActionSupport{
private BookManage bookManage;
public void setBookManage(BookManage bookManage) {
this.bookManage = bookManage;
}
@SuppressWarnings("unchecked")
public String execute(){
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
HttpSession session = request.getSession();
String bookId = request.getParameter("bookId");
List<Book> shoppingBook = new ArrayList<Book>();
if(session.getAttribute("shoppingBook") == null){
session.setAttribute("shoppingBook", shoppingBook);
}
else{
shoppingBook = (List<Book>) session.getAttribute("shoppingBook");
}
int i = 0;
for(Book book : shoppingBook){
if(bookId.equals(book.getBookId()+"")){
i++;
}
}
if(i == 0){
Book book = bookManage.findBook(Integer.parseInt(bookId));
book.setBookAmount(1);
Bargain bargain = null;
bargain = bookManage.isBargain(Integer.parseInt(bookId));
if(bargain != null){
book.setBookPrice(bargain.getBookNewPrice());
}
shoppingBook.add(book);
double totalMoney = 0;
if(session.getAttribute("totalMoney") == null){
session.setAttribute("totalMoney", book.getBookPrice());
}else{
totalMoney = (Double) session.getAttribute("totalMoney");
totalMoney += book.getBookPrice();
session.removeAttribute("totalMoney");
session.setAttribute("totalMoney", totalMoney);
}
session.removeAttribute("shoppingBook");
session.setAttribute("shoppingBook", shoppingBook);
}
try {
response.sendRedirect("../singleBook.jsp?bookId="+bookId);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}3.3.11 SingleBookAction
package com.huizhi.action; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import dao.BookManage;
import entity.*; @SuppressWarnings("serial")
public class SingleBookAction extends ActionSupport{ private BookManage bookManage; public void setBookManage(BookManage bookManage) {
this.bookManage = bookManage;
} public String execute(){
HttpServletRequest request = ServletActionContext.getRequest();
String bookId = request.getParameter("bookId");
int bookIdInt = Integer.parseInt(bookId);
Book book = new Book();
book = bookManage.findBook(bookIdInt);
Bargain bargain = null;
bargain = bookManage.isBargain(bookIdInt);
if(bargain == null){
book.setBookNewPrice(book.getBookPrice());
}else{
book.setBookNewPrice(bargain.getBookNewPrice());
}
request.setAttribute("singleBook", book);
return null;
}
}3.3.12 SingleOrdersAction
package com.huizhi.action; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import java.util.*;
import dao.*;
import entity.*;
@SuppressWarnings("serial")
public class SingleOrdersAction extends ActionSupport{ private OrdersManage ordersManage;
private BookManage bookManage; public void setOrdersManage(OrdersManage ordersManage) {
this.ordersManage = ordersManage;
} public void setBookManage(BookManage bookManage) {
this.bookManage = bookManage;
} public String execute(){
HttpServletRequest request = ServletActionContext.getRequest();
String ordersId = request.getParameter("ordersId");
int ordersIdInt = Integer.parseInt(ordersId);
Orders orders = new Orders();
orders = ordersManage.findOrders(ordersIdInt);
List<Ordersbook> allOrdersbookByOrders = new ArrayList<Ordersbook>();
allOrdersbookByOrders = ordersManage.allOrdersbookByOrders(ordersIdInt);
List<Book> bookList = new ArrayList<Book>();
for(Ordersbook ordersbook : allOrdersbookByOrders){
Book book = ordersbook.getBook();
Bargain bargain = null;
bargain = bookManage.isBargain(book.getBookId());
if(bargain != null){
book.setBookPrice(bargain.getBookNewPrice());
}
book.setBookAmount(ordersbook.getBookAmount());
bookList.add(book);
}
request.setAttribute("bookList", bookList);
request.setAttribute("orders", orders);
return null;
} }3.3.13 UpdateBookAction
package com.huizhi.action; import java.io.File;
import java.text.*;
import java.util.*;
import java.util.Date; import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import dao.BookManage;
import entity.*; @SuppressWarnings("serial")
public class UpdateBookAction extends ActionSupport{ private int bookId;
private String bookName;
private String bookAuthor;
private String bookPress;
private String bookRemark;
private int typeId;
private int bookAmount;
private double bookPrice;
private BookManage bookManage; private File doc;
private String fileName;
private String contentType;
private String dir;
private String targetFileName; public void setDoc(File file) {
this.doc = file;
} public void setDocFileName(String fileName) {
this.fileName = fileName;
}
public void setDocContentType(String contentType) {
this.contentType = contentType;
} public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getTargetFileName() {
return targetFileName;
}
public void setTargetFileName(String targetFileName) {
this.targetFileName = targetFileName;
}
private String generateFileName(String fileName){
DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
String formatDate = format.format(new Date());
int random = new Random().nextInt(100000);
int position = fileName.lastIndexOf(".");
String extension = fileName.substring(position);
return formatDate+random+extension;
} 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 getBookAuthor() {
return bookAuthor;
}
public void setBookAuthor(String bookAuthor) {
this.bookAuthor = bookAuthor;
}
public String getBookPress() {
return bookPress;
}
public void setBookPress(String bookPress) {
this.bookPress = bookPress;
}
public String getBookRemark() {
return bookRemark;
}
public void setBookRemark(String bookRemark) {
this.bookRemark = bookRemark;
}
public int getTypeId() {
return typeId;
}
public void setTypeId(int typeId) {
this.typeId = typeId;
}
public int getBookAmount() {
return bookAmount;
}
public void setBookAmount(int bookAmount) {
this.bookAmount = bookAmount;
}
public double getBookPrice() {
return bookPrice;
}
public void setBookPrice(double bookPrice) {
this.bookPrice = bookPrice;
}
public void setBookManage(BookManage bookManage) {
this.bookManage = bookManage;
}
@SuppressWarnings("deprecation")
public String execute(){
System.out.println(bookId);
Book book = bookManage.findBook(bookId);
System.out.println(book);
if(doc != null){
System.out.println("asd");
String realPath = ServletActionContext.getRequest().getRealPath("/upload");
String targetDirectory = realPath;
targetFileName =generateFileName(fileName);
setDir(targetDirectory+"\\"+targetFileName);
File target = new File(targetDirectory,targetFileName);
try {
FileUtils.copyFile(doc, target);
book.setBookPicture(targetFileName);//图片地址
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("ssss");
book.setBookName(bookName);
book.setBookAuthor(bookAuthor);
book.setBookPress(bookPress);
book.setBookRemark(bookRemark);
book.setBookPrice(bookPrice);
book.setBookAmount(bookAmount);
Type type = bookManage.findType(typeId);
book.setType(type);//类别
bookManage.updateBook(book);
return SUCCESS;
}
}3.3.14 UpdateCartAction
package com.huizhi.action; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import java.util.*;
import entity.*; @SuppressWarnings("serial")
public class UpdateCartAction extends ActionSupport{ @SuppressWarnings("unchecked")
public String execute(){
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
HttpSession session = request.getSession();
String updateType = request.getParameter("updateType");
List<Book> shoppingBook = (List<Book>) session.getAttribute("shoppingBook");
double totalMoney = 0;
totalMoney =(Double) session.getAttribute("totalMoney");
if("update".equals(updateType)){
String bookId = request.getParameter("bookId");
String bookAmount = request.getParameter("bookAmount");
for(Book book : shoppingBook){
if(bookId.equals(book.getBookId()+"")){
totalMoney += (Integer.parseInt(bookAmount)-book.getBookAmount())*book.getBookPrice();
book.setBookAmount(Integer.parseInt(bookAmount));
}
}
}
if("delete".equals(updateType)){
String bookId = request.getParameter("bookId");
Iterator<Book> iter = shoppingBook.iterator();
while(iter.hasNext()){
Book book = (Book)iter.next();
if(bookId.equals(book.getBookId()+"")){
totalMoney -= book.getBookAmount()*book.getBookPrice();
iter.remove();
}
}
}
session.removeAttribute("shoppingBook");
session.setAttribute("shoppingBook", shoppingBook);
session.removeAttribute("totalMoney");
session.setAttribute("totalMoney", totalMoney);
try {
response.sendRedirect("../shoppingCart.jsp");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}3.3.15 UserExitAction
package com.huizhi.action; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport; @SuppressWarnings("serial")
public class UserExitAction extends ActionSupport{ public String execute(){
String page = "firstPage";
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = request.getSession();
String userType = request.getParameter("userType");
if("ordinaryUser".equals(userType)){
session.removeAttribute("loginUser");
}else if("manager".equals(userType)){
session.removeAttribute("managerLoginName");
page = "managerLogin";
}else{
page = "error";
}
return page;
}
}3.3.16 UserInformationAction
package com.huizhi.action; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import dao.PersonManage;
import entity.User; @SuppressWarnings("serial")
public class UserInformationAction extends ActionSupport{ private PersonManage personManage; public PersonManage getPersonManage() {
return personManage;
} public void setPersonManage(PersonManage personManage) {
this.personManage = personManage;
}
public String execute(){
HttpServletRequest request = ServletActionContext.getRequest();
String userIdString = request.getParameter("userId");
int userId = Integer.parseInt(userIdString);
User user = personManage.findUser(userId);
request.setAttribute("user", user);
return null;
}
}3.3.17 UserManageAction
package com.huizhi.action; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import dao.PersonManage;
import entity.*; @SuppressWarnings("serial")
public class UserManageAction extends ActionSupport{ private String userNickname;
private int sexId;
private String userEmail;
private String userPhone;
private String userAddress;
private String userRemark; private String userPassword;
private String newUserPassword;
private String reNewUserPassword; private PersonManage personManage;
public String getUserNickname() {
return userNickname;
}
public void setUserNickname(String userNickname) {
this.userNickname = userNickname;
}
public String getUserEmail() {
return userEmail;
}
public int getSexId() {
return sexId;
}
public void setSexId(int sexId) {
this.sexId = sexId;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
public String getUserRemark() {
return userRemark;
}
public void setUserRemark(String userRemark) {
this.userRemark = userRemark;
}
public void setPersonManage(PersonManage personManage) {
this.personManage = personManage;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getNewUserPassword() {
return newUserPassword;
}
public void setNewUserPassword(String newUserPassword) {
this.newUserPassword = newUserPassword;
}
public String getReNewUserPassword() {
return reNewUserPassword;
}
public void setReNewUserPassword(String reNewUserPassword) {
this.reNewUserPassword = reNewUserPassword;
}
public String updateUserInfor(){
String page = "fail";
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = request.getSession();
User user = (User)session.getAttribute("loginUser");
if(user == null){
page = "error";
}else{
user.setUserNickname(userNickname);
Sex sex = personManage.findSex(sexId);
user.setSex(sex);
user.setUserEmail(userEmail);
user.setUserPhone(userPhone);
user.setUserAddress(userAddress);
user.setUserRemark(userRemark);
int i = 0 ;
i = personManage.updateUserInfor(user);
if(i == 1){
page="success";
session.removeAttribute("loginUser");
session.setAttribute("loginUser", user);
}
if(i == 0){
page = "error";
}
}
return page;
}
public String updateUserPassword(){
String page="fail";
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = request.getSession();
User user = (User)session.getAttribute("loginUser");
if(user == null){
page = "error";
}else{
if(user.getUserPassword().equals(userPassword)){
if(newUserPassword.equals(reNewUserPassword)){
user.setUserPassword(newUserPassword);
int i = 0;
i = personManage.updateUserInfor(user);
if( i == 1){
page="success";
session.removeAttribute("loginUser");
session.setAttribute("loginUser", user);
}
if(i == 0){
page = "error";
}
}
}
}
return page;
}
}至此,核心代码已经结束,慢慢看应该问题不大。
四 XML配置
xml是SSH2中最关键的一步,好多情况下代码正确,但是依然404,就是因为配置原因4.1 struts.xml
由于struts的对象交给了Spring管理,因此这里的class引用写的不是类的地址,是Spring配置文件中类地址对应的名称这个配置文件使用myeclipse可以清楚的看到个个action之间的联系<!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.objectFactory" value="spring" />
<constant name="struts.i18n.encoding" value="gb2312"/>
<constant name="struts.custom.i18n.resources" value="globalMessages"/> <package name="default" extends="struts-default">
<interceptors>
<interceptor name="userLoginCheck" class="interceptor.UserLoginCheck"></interceptor>
</interceptors>
<global-results>
<result name="error" type="redirect">/error.html </result>
</global-results>
<action name="enrollAction" class="EnrollAction">
<result name="input">/enroll.jsp </result>
<result name="success">/login.jsp</result>
</action> <action name="loginAction" class="LoginAction" method="loginCheck">
<result name="fail">/login.jsp </result>
<result name="success" type="redirect">/firstPage.jsp</result>
</action> <action name="managerLoginAction" class="LoginAction" method="managerLoginCheck">
<result name="fail">/managerLogin.jsp </result>
<result name="success" type="redirect">/manage/manageWelcome.jsp</result>
</action> <action name="leftAction" class="LeftAction">
</action> <action name="allBookAction" class="AllBookAction">
</action> <action name="singleBookAction" class="SingleBookAction">
</action> <action name="bookAction" class="BookAction">
<interceptor-ref name="fileUpload">
<param name="allowedTypes">
image/jpeg,image/gif,image/bmp,image/png
</param>
<param name="maximumSize">20000</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="input">/manage/addBook.jsp </result>
<result name="success" type="redirect">/manage/addBook.jsp </result>
</action> <action name="oneTypeAction" class="OneTypeAction">
<result name="oneType" type="redirect">/oneType.jsp </result>
</action> <action name="userInforAction" class="UserManageAction" method="updateUserInfor">
<result name="success" type="redirect">/personalInformation.jsp </result>
<result name="fail" >/personalInformation.jsp </result>
</action> <action name="updatePasswordAction" class="UserManageAction" method="updateUserPassword">
<result name="success" type="redirect">/personalInformation.jsp </result>
<result name="fail">/updatePassword.jsp </result>
</action> <action name="ordersManageAction" class="OrdersManageAction">
<result name="success" type="redirect">/allOrders.jsp </result>
</action> <action name="ordersAction" class="OrdersAction">
</action> <action name="userExitAction" class="UserExitAction">
<result name="firstPage" type="redirect">/firstPage.jsp </result>
<result name="managerLogin" type="redirect">/managerLogin.jsp </result>
</action> <action name="shoppingCartAction" class="ShoppingCartAction">
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="userLoginCheck"></interceptor-ref>
<result name="login" type="redirect">/login.jsp </result>
</action> <action name="updateCartAction" class="UpdateCartAction">
</action> <action name="singleOrdersAction" class="SingleOrdersAction">
</action> <action name="allOrdersAction" class="AllOrdersAction">
</action>
<action name="dealOrdersAction" class="DealOrdersAction">
</action>
<action name="userInformationAction" class="UserInformationAction">
</action>
<action name="updateBookAction" class="UpdateBookAction">
<interceptor-ref name="fileUpload">
<param name="allowedTypes">
image/jpeg,image/gif,image/bmp,image/png
</param>
<param name="maximumSize">20000</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="input">/manage/updateBook.jsp?bookId=${bookId}</result>
<result name="success" type="redirect">/manage/updateBook.jsp?bookId=${bookId}</result>
</action>
</package>
</struts>4.2 applicationContext.xml
Spring的配置文件,关键在于IOC的各个注入关系<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="candy" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url"
value="jdbc:mysql://localhost:3306/bookstore">
</property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="candy" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>entity/Bargain.hbm.xml</value>
<value>entity/Book.hbm.xml</value>
<value>entity/Manager.hbm.xml</value>
<value>entity/Orders.hbm.xml</value>
<value>entity/Recommended.hbm.xml</value>
<value>entity/Sex.hbm.xml</value>
<value>entity/Type.hbm.xml</value>
<value>entity/User.hbm.xml</value>
<value>entity/Ordersbook.hbm.xml</value></list>
</property>
</bean>
<bean id="personManage" class="dao.PersonManage" abstract="false"
lazy-init="default" autowire="default" dependency-check="default">
<property name="sessionFactory" >
<ref local="sessionFactory"/>
</property>
</bean>
<bean id="bookManage" class="dao.BookManage" abstract="false"
lazy-init="default" autowire="default" dependency-check="default">
<property name="sessionFactory" >
<ref local="sessionFactory"/>
</property>
</bean>
<bean id="ordersManage" class="dao.OrdersManage" abstract="false"
lazy-init="default" autowire="default" dependency-check="default">
<property name="sessionFactory" >
<ref local="sessionFactory"/>
</property>
</bean>
<bean id="LoginAction" class="com.huizhi.action.LoginAction" scope="prototype">
<property name="personManage">
<ref bean="personManage" />
</property>
</bean>
<bean id="EnrollAction" class="com.huizhi.action.EnrollAction" scope="prototype">
<property name="personManage">
<ref bean="personManage" />
</property>
</bean>
<bean id="LeftAction" class="com.huizhi.action.LeftAction" scope="prototype">
<property name="bookManage">
<ref bean="bookManage" />
</property>
</bean>
<bean id="AllBookAction" class="com.huizhi.action.AllBookAction" scope="prototype">
<property name="bookManage">
<ref bean="bookManage" />
</property>
</bean>
<bean id="SingleBookAction" class="com.huizhi.action.SingleBookAction" scope="prototype">
<property name="bookManage">
<ref bean="bookManage" />
</property>
</bean>
<bean id="BookAction" class="com.huizhi.action.BookAction" scope="prototype">
<property name="bookManage">
<ref bean="bookManage" />
</property>
</bean>
<bean id="OneTypeAction" class="com.huizhi.action.OneTypeAction" scope="prototype">
<property name="bookManage">
<ref bean="bookManage" />
</property>
</bean>
<bean id="UserManageAction" class="com.huizhi.action.UserManageAction" scope="prototype">
<property name="personManage">
<ref bean="personManage" />
</property>
</bean>
<bean id="UserExitAction" class="com.huizhi.action.UserExitAction" scope="prototype">
</bean>
<bean id="UpdateCartAction" class="com.huizhi.action.UpdateCartAction" scope="prototype">
</bean>
<bean id="ShoppingCartAction" class="com.huizhi.action.ShoppingCartAction" scope="prototype">
<property name="bookManage">
<ref bean="bookManage" />
</property>
</bean>
<bean id="SingleOrdersAction" class="com.huizhi.action.SingleOrdersAction" scope="prototype">
<property name="bookManage">
<ref bean="bookManage" />
</property>
<property name="ordersManage">
<ref bean="ordersManage" />
</property>
</bean>
<bean id="OrdersManageAction" class="com.huizhi.action.OrdersManageAction" scope="prototype">
<property name="ordersManage">
<ref bean="ordersManage" />
</property>
</bean>
<bean id="OrdersAction" class="com.huizhi.action.OrdersAction" scope="prototype">
<property name="ordersManage">
<ref bean="ordersManage" />
</property>
</bean>
<bean id="AllOrdersAction" class="com.huizhi.action.AllOrdersAction" scope="prototype">
<property name="ordersManage">
<ref bean="ordersManage" />
</property>
</bean>
<bean id="DealOrdersAction" class="com.huizhi.action.DealOrdersAction" scope="prototype">
<property name="ordersManage">
<ref bean="ordersManage" />
</property>
</bean>
<bean id="UserInformationAction" class="com.huizhi.action.UserInformationAction" scope="prototype">
<property name="personManage">
<ref bean="personManage" />
</property>
</bean>
<bean id="UpdateBookAction" class="com.huizhi.action.UpdateBookAction" scope="prototype">
<property name="bookManage">
<ref bean="bookManage" />
</property>
</bean>
</beans>4.3 web.xml
这个配置文件写起来比较简单,基本上可以通过Myeclipse自动生成,不过注意,Spring的监听器需要自己写上,不会自动生成<?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"> <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param> <listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>managerLogin</filter-name>
<filter-class>filter.ManagerLoginCheck</filter-class>
</filter>
<filter-mapping>
<filter-name>managerLogin</filter-name>
<url-pattern>/manage/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>五 Jsp代码
JSP为显示端的问题,细节很多很杂,这里就不关注了。感兴趣的可以找我要源码直接对比看。六 总结
至此,一个SSH2小型项目结束。总结一下:1.实体类是基础,注意实体类与数据库的映射关系2.需求分析很重要,否则无法摸清楚业务间逻辑关系3.每个Action都支撑起整个业务逻辑,最好对比JSP代码线性写。4.要有宏观思路,培养产品经理的思想。