SSH2項目網上書店系統手把手教學_Struts2+Spring+Hibernate整合開發

一 序言

鑑於目前J2EE的火熱程度,SSH2是每一個學生畢業前都必須掌握的一門技術,因此在這裏我就使用SSH2技術作一個小型項目,和你們一塊兒學習。html

SSH2技術的基礎概論就再也不提了,直接說特色吧。java

1)編程簡單,使用SSH2技術使得JAVA代碼的編程變得異常簡單,幾個模塊一劃分,功能不言自明。mysql

2)控制邏輯有所優化,這裏說有所優化是指對比severlet來說,在SSH2項目編寫過程當中,關於XML的配置文件仍是比較複雜的。程序員

3)界面編寫繁瑣,其實這不是SSH2負責的領域了,可是做爲一個系統必須有MVC,其中的V不可逾越,所以咱們儘可能多關注MVJSP頁面的編程瞭解便可。web


應你們要求,現提供源碼下載,僅做參考:源碼下載
spring

二 系統分析

做爲一個項目,完成必定的功能便可,過多的追究冷門細節意義不大。所以,項目中使用的SSH2都是基本功能,個人學習過程全靠百度,這裏簡單說一下SSH2各部門的做用。sql

Struts2負責控制業務邏輯,即怎麼跳轉頁面,功能怎麼組裝。數據庫

Hibernate負責將對象與數據庫關係映射,使咱們可使用面向對象的方法訪問數據庫。apache

Spring負責IoCAOP,屬於大管家級別,貫穿整個項目。即管理全部對象的生成和負責事務管理。編程

三 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以及花樣CRUD
package 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.要有宏觀思路,培養產品經理的思想。
相關文章
相關標籤/搜索