Struts2、Spring和Hibernate應用實例

   Struts作爲MVC 2Web框架,自推出以來不斷受到開發者的追捧,得到廣泛的應用。作爲最成功的Web框架,Struts自然擁有衆多的優點:MVC 2模型的使用、功能齊全的標誌庫(Tag Library)、開放源代碼。而Spring的出現,在某些方面極大的方面了Struts的開發。同時,Hibernate作爲對象持久化的框架,能顯示的提高軟件開發的效率與生產力。這三種流行框架的整合應用,可以發揮它們各自的優勢,使軟件開發更加的快速與便捷。

struts2發佈已經很久了,但關於如何使用它的教程及實例並不多。特別是與SpringHibernate等流行框架的集成,並不多見。現在就將筆者使用Myeclipse工具應用struts2 + spring2 + hibernate3 實現CRUD操作的步驟一一紀錄下來,爲初學者少走彎路略盡綿薄之力!在本文中,筆者將Struts2.0.6Spring2.0.6Hibernate3.1進行整合,希望通過這樣的整合示例,讓讀者瞭解這些框架各自的特點,以便於在自己的項目中,根據實際情況,儘快的過渡到Struts2的時代。本文的內容基於Struts2.0.6

 

一、準備工作

 

spring2與1.x區別不大,可以平滑的過度,筆者也是把spring1.28換成了spring2.0.6,算是升級到spring 2.0了。struts2基本就是webwork2.2,與以前的struts1.x可以說沒任何關係了。因爲是第一次用struts2,也是第一次用webwork,所以有很多不完善,不規範的地方,還望大家來拍磚。

開發環境:MyEclipse5.0+Eclipse3.2+JDK5.0+

Tomcat5.5+struts2+Spring2.0.6+Hibernate3.1。本示例通過對一個圖書進行管理的系統,提供基本的增加、刪除、修改、查詢等功能。

lib包需要以下右圖所示的這些包。其中Struts2.0.6的下載地址爲:

http://people.apache.org/builds/struts/2.0.6

Hibernate3.1的下載地址爲:

http://www.hibernate.org

spring2.0.6的下載地址爲:

http://www.springframework.org

使用的數據庫爲mysql 5.0,使用的JDBC驅動JAR包爲:mysql-connection-java-5.0.4-bin

創建數據表的sql語句爲:

create database game 

CREATE TABLE `books` (

`book_id` int(11) NOT NULL default '0',

`book_name` varchar(200) character set gb2312 default NULL,

`book_author` varchar(100) character set gb2312 default NULL,

`book_publish` varchar(100) character set gb2312 default NULL,

`book_date` date default NULL,

`book_isbn` varchar(20) default NULL,

`book_page` int(11) default NULL,

`book_price` decimal(10,2) default NULL,

`book_content` varchar(100) character set gb2312 default NULL,

PRIMARY KEY  (`book_id`)

) ENGINE=InnoDB DEFAULT CHARSET=gbk ROW_FORMAT=COMPRESSED;

 

二、建立公共類 

1、AbstractAction

Struts2和Struts1.x的差別,最明顯的就是Struts2是一個pull-MVC架構。Struts1.x 必須繼承org.apache.struts.action.Action或者其子類,表單數據封裝在FormBean中。Struts 2無須繼承任何類型或實現任何接口,表單數據包含在Action中,通過GetterSetter獲取。

雖然,在理論上Struts2Action無須實現任何接口或者是繼承任何的類,但是,在實際編程過程中,爲了更加方便的實現Action,大多數情況下都會繼承com.opensymphony.xwork2.ActionSupport類,並且重載(Override)此類裏的String execute()方法。因此先建立抽象類,以供其它Action類使用。

 

package com.sterning.commons;

import com.opensymphony.xwork2.ActionSupport;

public class AbstractAction extends ActionSupport {

}

com.sterning.commons.AbstractAction.java

參考JavaDoc,可知ActionSupport類實現了接口:

com.opensymphony.xwork2.Action

com.opensymphony.xwork2.LoaleProvider

com.opensymphony.xwork2.TextProvider

com.opensymphony.xwork2.Validateable

com.opensymphony.xwork2.ValidationAware

com.uwyn.rife.continuations.ContinuableObject

java.io.Searializable

java.lang.Cloneable

 

2、Pager分頁類

爲了增加程序的分頁功能,特意建立共用的分頁類。

 

package com.sterning.commons;

import java.math.*;

public class Pager {

private int totalRows; //總行數

    private int pageSize = 5; //每頁顯示的行數

    private int currentPage; //當前頁號

    private int totalPages; //總頁數

    private int startRow; //當前頁在數據庫中的起始行

 

public Pager() {

}

public Pager(int _totalRows) {

totalRows = _totalRows;

totalPages=totalRows/pageSize;

int mod=totalRows%pageSize;

if(mod>0){

totalPages++;

}

currentPage = 1;

startRow = 0;

}

public int getStartRow() {

return startRow;

}

public int getTotalPages() {

return totalPages;

}

public int getCurrentPage() {

return currentPage;

}

public int getPageSize() {

return pageSize;

}

public void setTotalRows(int totalRows) {

this.totalRows = totalRows;

}

public void setStartRow(int startRow) {

this.startRow = startRow;

}

public void setTotalPages(int totalPages) {

this.totalPages = totalPages;

}

public void setCurrentPage(int currentPage) {

this.currentPage = currentPage;

}

public void setPageSize(int pageSize) {

this.pageSize = pageSize;

}

public int getTotalRows() {

return totalRows;

}

public void first() {

currentPage = 1;

startRow = 0;

}

public void previous() {

if (currentPage == 1) {

return;

}

currentPage--;

startRow = (currentPage - 1) * pageSize;

}

public void next() {

if (currentPage < totalPages) {

currentPage++;

}

startRow = (currentPage - 1) * pageSize;

}

public void last() {

currentPage = totalPages;

startRow = (currentPage - 1) * pageSize;

}

public void refresh(int _currentPage) {

currentPage = _currentPage;

if (currentPage > totalPages) {

last();

}

}

}

 

com.sterning.commons.Pager.java

同時,採用PagerService類來發布成爲分頁類服務PagerService,代碼如下:

 

package com.sterning.commons;

public class PagerService {

public Pager getPager(String currentPage,String pagerMethod,int totalRows) {

//    定義pager對象,用於傳到頁面

        Pager pager = new Pager(totalRows);

//    如果當前頁號爲空,表示爲首次查詢該頁

//    如果不爲空,則刷新pager對象,輸入當前頁號等信息

        if (currentPage != null) {

pager.refresh(Integer.parseInt(currentPage));

}

//    獲取當前執行的方法,首頁,前一頁,後一頁,尾頁。

        if (pagerMethod != null) {

if (pagerMethod.equals("first")) {

pager.first();

} else if (pagerMethod.equals("previous")) {

pager.previous();

} else if (pagerMethod.equals("next")) {

pager.next();

} else if (pagerMethod.equals("last")) {

pager.last();

}

}

return pager;

}

}

 

com.sterning.commons.PagerService.java 

 

 

三、 建立數據持久化層

 

1、編寫實體類Booksbooks.hbm.xml映射文件。

 

package com.sterning.books.model;

import java.util.Date;

public class Books {

//    Fields 

    private String bookId;//編號

    private String bookName;//書名

    private String bookAuthor;//作者

    private String bookPublish;//出版社

    private Date bookDate;//出版日期

    private String bookIsbn;//ISBN

    private String bookPage;//頁數

    private String bookPrice;//價格

    private String bookContent;//內容提要

//    Constructors

    public Books(){}

//    Property accessors

 

    public String getBookId() {

return bookId;

}

public void setBookId(String 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 getBookContent() {

return bookContent;

}

public void setBookContent(String bookContent) {

this.bookContent = bookContent;

}

public Date getBookDate() {

return bookDate;

}

public void setBookDate(Date bookDate) {

this.bookDate = bookDate;

}

public String getBookIsbn() {

return bookIsbn;

}

public void setBookIsbn(String bookIsbn) {

this.bookIsbn = bookIsbn;

}

public String getBookPage() {

return bookPage;

}

public void setBookPage(String bookPage) {

this.bookPage = bookPage;

}

public String getBookPrice() {

return bookPrice;

}

public void setBookPrice(String bookPrice) {

this.bookPrice = bookPrice;

}

public String getBookPublish() {

return bookPublish;

}

public void setBookPublish(String bookPublish) {

this.bookPublish = bookPublish;

}

}

 

com.sterning.books.model.Books.java

       接下來要把實體類Books的屬性映射到books表,編寫下面的books.hbm.xml文件:

 

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

     <class name="com.sterning.books.model.Books" table="books" >

         <id name="bookId" type="string">

            <column name="book_id" length="5" />

            <generator class="assigned" />

        </id>

        <property name="bookName" type="string">

            <column name="book_name" length="100" />

        </property>

         <property name="bookAuthor" type="string">

            <column name="book_author" length="100" />

        </property>

        <property name="bookPublish" type="string">

            <column name="book_publish" length="100" />

        </property>

         <property name="bookDate" type="java.sql.Timestamp">

            <column name="book_date" length="7" />

        </property>

          <property name="bookIsbn" type="string">

            <column name="book_isbn" length="20" />

        </property>

        <property name="bookPage" type="string">

            <column name="book_page" length="11" />

        </property>

        <property name="bookPrice" type="string">

            <column name="book_price" length="4" />

        </property>

<property name="bookContent" type="string">

            <column name="book_content" length="100" />

        </property>

     </class>

</hibernate-mapping>

 

com.sterning.books.model.books.hbm.xml

2、hibernate.cfg.xml配置文件如下:(注意它的位置在scr/hibernate.cfg.xml

 

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

    <property name="show_sql">true</property>

    <mapping resource="com/sterning/books/model/books.hbm.xml"></mapping>

</session-factory>

</hibernate-configuration>

 

Com.sterning.bean.hibernate.hibernate.cfg.xml 

 

四、 建立DAO

 

DAO訪問層負責封裝底層的數據訪問細節,不僅可以使概念清晰,而且可以提高開發效率。

1、建立DAO的接口類:BooksDao

 

package com.sterning.books.dao.iface;

import java.util.List;

import com.sterning.books.model.Books;

public interface BooksDao {

List getAll();//獲得所有記錄

    List getBooks(int pageSize, int startRow);//獲得所有記錄

    int getRows();//獲得總行數

    int getRows(String fieldname,String value);//獲得總行數

    List queryBooks(String fieldname,String value);//根據條件查詢

    List getBooks(String fieldname,String value,int pageSize, int startRow);//根據條件查詢

    Books getBook(String bookId);//根據ID獲得記錄

    String getMaxID();//獲得最大ID

    void addBook(Books book);//添加記錄

    void updateBook(Books book);//修改記錄

    void deleteBook(Books book);//刪除記錄    

}

 

com.sterning.books.dao.iface.BooksDao.java 

 

2、實現此接口的類文件,BooksMapDao

 

package com.sterning.books.dao.hibernate;

import java.sql.SQLException;

import java.util.Iterator;

import java.util.List;

import org.hibernate.HibernateException;

import org.hibernate.Query;

import org.hibernate.Session;

import org.springframework.orm.hibernate3.HibernateCallback;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.sterning.books.dao.iface.BooksDao;

import com.sterning.books.model.Books;

import com.sterning.commons.PublicUtil;

/**

* @author cwf

*

*/

public class BooksMapDao extends HibernateDaoSupport implements BooksDao {

public BooksMapDao(){}

/**

* 函數說明:添加信息

* 參數說明:對象

* 返回值:

*/

    public void addBook(Books book) {

this.getHibernateTemplate().save(book);

}

/**

* 函數說明:刪除信息

* 參數說明: 對象

* 返回值:

*/

    public void deleteBook(Books book) {

this.getHibernateTemplate().delete(book);

}

/**

* 函數說明:獲得所有的信息

* 參數說明:

* 返回值:信息的集合

*/

    public List getAll() {

String sql="FROM Books ORDER BY bookName";

return this.getHibernateTemplate().find(sql);

}

/**

* 函數說明:獲得總行數

* 參數說明:

* 返回值:總行數

*/

    public int getRows() {

String sql="FROM Books ORDER BY bookName";

List list=this.getHibernateTemplate().find(sql);

return list.size();

}

/**

* 函數說明:獲得所有的信息

* 參數說明:

* 返回值:信息的集合

*/

    public List getBooks(int pageSize, int startRow) throws HibernateException {

final int pageSize1=pageSize;

final int startRow1=startRow;

return this.getHibernateTemplate().executeFind(new HibernateCallback(){

public List doInHibernate(Session session) throws HibernateException, SQLException {

// TODO 自動生成方法存根

                Query query=session.createQuery("FROM Books ORDER BY bookName");

query.setFirstResult(startRow1);

query.setMaxResults(pageSize1);

return query.list();

}

});

}

/**

* 函數說明:獲得一條的信息

* 參數說明: ID

* 返回值:對象

*/

    public Books getBook(String bookId) {

return (Books)this.getHibernateTemplate().get(Books.class,bookId);

}

/**

* 函數說明:獲得最大ID

* 參數說明:

* 返回值:最大ID

*/

    public String getMaxID() {

String date=PublicUtil.getStrNowDate();

String sql="SELECT MAX(bookId)+1 FROM Books  ";

String noStr = null;

List ll = (List) this.getHibernateTemplate().find(sql);

Iterator itr = ll.iterator();

if (itr.hasNext()) {

Object noint = itr.next();

if(noint == null){

noStr = "1";

}else{

noStr = noint.toString();

}

}

if(noStr.length()==1){

noStr="000"+noStr;

}else if(noStr.length()==2){

noStr="00"+noStr;

}else if(noStr.length()==3){

noStr="0"+noStr;

}else{

noStr=noStr;

}

return noStr;

}

/**

* 函數說明:修改信息

* 參數說明: 對象

* 返回值:

*/

    public void updateBook(Books pd) {

this.getHibernateTemplate().update(pd);

}

/**

* 函數說明:查詢信息

* 參數說明: 集合

* 返回值:

*/

    public List queryBooks(String fieldname,String value) {

System.out.println("value: "+value);

String sql="FROM Books where "+fieldname+" like '%"+value+"%'"+"ORDER BY bookName";

return this.getHibernateTemplate().find(sql);

}

/**

* 函數說明:獲得總行數

* 參數說明:

* 返回值:總行數

*/

    public int getRows(String fieldname,String value) {

String sql="";

if(fieldname==null||fieldname.equals("")||fieldname==null||fieldname.equals(""))

sql="FROM Books ORDER BY bookName";

else

sql="FROM Books where "+fieldname+" like '%"+value+"%'"+"ORDER BY bookName";

List list=this.getHibernateTemplate().find(sql);

return list.size();

}

/**

* 函數說明:查詢信息

* 參數說明: 集合

* 返回值:

*/

 

public List getBooks(String fieldname,String value,int pageSize, int startRow) {

final int pageSize1=pageSize;

final int startRow1=startRow;

final String queryName=fieldname;

final String queryValue=value;

String sql="";

if(queryName==null||queryName.equals("")||queryValue==null||queryValue.equals(""))

sql="FROM Books ORDER BY bookName";

else

sql="FROM Books where "+fieldname+" like '%"+value+"%'"+"ORDER BY bookName";

final String sql1=sql;

return this.getHibernateTemplate().executeFind(new HibernateCallback(){

public List doInHibernate(Session session) throws HibernateException, SQLException {

// TODO 自動生成方法存根

                Query query=session.createQuery(sql1);

query.setFirstResult(startRow1);

query.setMaxResults(pageSize1);

return query.list();

}

});

}

}

五、業務邏輯層

 

在業務邏輯層需要認真思考每個業務邏輯所能用到的持久層對象和DAODAO層之上是業務邏輯層,DAO類可以有很多個,但業務邏輯類應該只有一個,可以在業務邏輯類中調用各個DAO類進行操作。

1、創建服務接口類IBookService

 

package com.sterning.books.services.iface;

 

import java.util.List;

 

import com.sterning.books.model.Books;

 

public interface IBooksService ...{

    List getAll();//獲得所有記錄

    List getBooks(int pageSize, int startRow);//獲得所有記錄

    int getRows();//獲得總行數

    int getRows(String fieldname,String value);//獲得總行數

    List queryBooks(String fieldname,String value);//根據條件查詢

    List getBooks(String fieldname,String value,int pageSize, int startRow);//根據條件查詢

    Books getBook(String bookId);//根據ID獲得記錄

    String getMaxID();//獲得最大ID

    void addBook(Books pd);//添加記錄

    void updateBook(Books pd);//修改記錄

    void deleteBook(String bookId);//刪除記錄    

}

com.sterning.books.services.iface.IBookService.java

 

2、實現此接口類:BookService

package com.sterning.books.services;

import java.util.List;

import com.sterning.books.dao.iface.BooksDao;

import com.sterning.books.model.Books;

import com.sterning.books.services.iface.IBooksService;

public class BooksService implements IBooksService{

private BooksDao booksDao;

public BooksService(){}

/**

* 函數說明:添加信息

* 參數說明:對象

* 返回值:

*/

    public void addBook(Books book) {

booksDao.addBook(book);

}

/**

* 函數說明:刪除信息

* 參數說明: 對象

* 返回值:

*/

    public void deleteBook(String bookId) {

Books book=booksDao.getBook(bookId);

booksDao.deleteBook(book);

}

/**

* 函數說明:獲得所有的信息

* 參數說明:

* 返回值:信息的集合

*/

    public List getAll() {

return booksDao.getAll();

}

/**

* 函數說明:獲得總行數

* 參數說明:

* 返回值:總行數

*/

    public int getRows() {

return booksDao.getRows();

}

/**

* 函數說明:獲得所有的信息

* 參數說明:

* 返回值:信息的集合

*/

    public List getBooks(int pageSize, int startRow) {

return booksDao.getBooks(pageSize, startRow);

}

/**

* 函數說明:獲得一條的信息

* 參數說明: ID

* 返回值:對象

*/

    public Books getBook(String bookId) {

return booksDao.getBook(bookId);

}

/**

* 函數說明:獲得最大ID

* 參數說明:

* 返回值:最大ID

*/

    public String getMaxID() {

return booksDao.getMaxID();

}

/**

* 函數說明:修改信息

* 參數說明: 對象

* 返回值:

*/

    public void updateBook(Books book) {

booksDao.updateBook(book);

}

/**

* 函數說明:查詢信息

* 參數說明: 集合

* 返回值:

*/

    public List queryBooks(String fieldname,String value) {

return booksDao.queryBooks(fieldname, value);

}

/**

* 函數說明:獲得總行數

* 參數說明:

* 返回值:總行數

*/

    public int getRows(String fieldname,String value) {

return booksDao.getRows(fieldname, value);

}

/**

* 函數說明:查詢信息

* 參數說明: 集合

* 返回值:

*/

    public List getBooks(String fieldname,String value,int pageSize, int startRow) {

return booksDao.getBooks(fieldname, value,pageSize,startRow);

}

public BooksDao getBooksDao() {

return booksDao;

}

public void setBooksDao(BooksDao booksDao) {

this.booksDao = booksDao;

}

}

 

六、 創建Action類:BookAction 

 

Struts 1.x經驗的朋友都知道ActionStruts的核心內容,當然Struts 2.0也不例外。不過,Struts 1.xStruts 2.0Action模型很大的區別。

 

  

 Struts 1.x

 Stuts 2.0

 

接口

 必須繼承org.apache.struts.action.Action或者其子類

 無須繼承任何類型或實現任何接口

 

表單數據

表單數據封裝在FormBean

表單數據包含在Action中,通過GetterSetter獲取

 

1、建立BookAction

 

package com.sterning.books.web.actions;

 

import java.util.Collection;

import com.sterning.books.model.Books;

import com.sterning.books.services.iface.IBooksService;

import com.sterning.commons.AbstractAction;

import com.sterning.commons.Pager;

import com.sterning.commons.PagerService;

 

public class BooksAction extends AbstractAction {

    

    private IBooksService booksService;

    private PagerService pagerService;

    private Books book;

    private Pager pager;

    protected Collection availableItems;

    protected String currentPage;

    protected String pagerMethod;

    protected String totalRows;

    protected String bookId;

    protected String queryName;

    protected String queryValue;

    protected String searchName;

    protected String searchValue;

    protected String queryMap;

    

    public String list() throws Exception {

        if(queryMap ==null||queryMap.equals("")){

            

        }else{

            String[] str=queryMap.split("~");

            this.setQueryName(str[0]);

            this.setQueryValue(str[1]);

        }

        

        System.out.println("asd"+this.getQueryValue());

        int totalRow=booksService.getRows(this.getQueryName(),this.getQueryValue());

        pager=pagerService.getPager(this.getCurrentPage(), this.getPagerMethod(), totalRow);

        this.setCurrentPage(String.valueOf(pager.getCurrentPage()));

        this.setTotalRows(String.valueOf(totalRow));

        availableItems=booksService.getBooks(this.getQueryName(),this.getQueryValue(),pager.getPageSize(), pager.getStartRow());

        

        this.setQueryName(this.getQueryName());

        this.setQueryValue(this.getQueryValue());

        

        this.setSearchName(this.getQueryName());

        this.setSearchValue(this.getQueryValue());

        

        return SUCCESS;         

    }

    

    public String load() throws Exception {

        if(bookId!=null)

            book = booksService.getBook(bookId);

        else

            bookId=booksService.getMaxID();

        return SUCCESS;

    }

    

    public String save() throws Exception {

        if(this.getBook().getBookPrice().equals("")){

            this.getBook().setBookPrice("0.0");

        }

        

        String id=this.getBook().getBookId();

        Books book=booksService.getBook(id);

        

        

        

        if(book == null)

            booksService.addBook(this.getBook());

        else

            booksService.updateBook(this.getBook());

        

        this.setQueryName(this.getQueryName());

        this.setQueryValue(this.getQueryValue());

        

        if(this.getQueryName()==null||this.getQueryValue()==null||this.getQueryName().equals("")||this.getQueryValue().equals("")){

            

        }else{

            queryMap=this.getQueryName()+"~"+this.getQueryValue();

        }        

        

        return SUCCESS;

    }

    

    public String delete() throws Exception {

        booksService.deleteBook(this.getBookId());

        

        if(this.getQueryName()==null||this.getQueryValue()==null||this.getQueryName().equals("")||this.getQueryValue().equals("")){

            

        }else{

            queryMap=this.getQueryName()+"~"+this.getQueryValue();

        }

        return SUCCESS;

    }    

    

    public Books getBook() {

        return book;

    }

 

    public void setBook(Books book) {

        this.book = book;

    }

 

    public IBooksService getBooksService() {

        return booksService;

    }

 

    public void setBooksService(IBooksService booksService) {

        this.booksService = booksService;

    }

 

    public Collection getAvailableItems() {

        return availableItems;

    }

 

    public String getCurrentPage() {

        return currentPage;

    }

 

    public void setCurrentPage(String currentPage) {

        this.currentPage = currentPage;

    }

 

    public String getPagerMethod() {

        return pagerMethod;

    }

 

    public void setPagerMethod(String pagerMethod) {

        this.pagerMethod = pagerMethod;

    }

 

    public Pager getPager() {

        return pager;

    }

 

    public void setPager(Pager pager) {

        this.pager = pager;

    }

 

    public String getTotalRows() {

        return totalRows;

    }

 

    public void setTotalRows(String totalRows) {

        this.totalRows = totalRows;

    }

        

    public String getBookId() {

        return bookId;

    }

 

    public void setBookId(String bookId) {

        this.bookId = bookId;

    }

 

    public String getQueryName() {

        return queryName;

    }

 

    public void setQueryName(String queryName) {

        this.queryName = queryName;

    }

 

    public String getQueryValue() {

        return queryValue;

    }

 

    public void setQueryValue(String queryValue) {

        this.queryValue = queryValue;

    }

    

    public String getSearchName() {

        return searchName;

    }

 

    public void setSearchName(String searchName) {

        this.searchName = searchName;

    }

 

    public String getSearchValue() {

        return searchValue;

    }

 

    public void setSearchValue(String searchValue) {

        this.searchValue = searchValue;

    }

    

    public String getQueryMap() {

        return queryMap;

    }

 

    public void setQueryMap(String queryMap) {

        this.queryMap = queryMap;

    }

    

    public PagerService getPagerService() {

        return pagerService;

    }

 

 

    public void setPagerService(PagerService pagerService) {

        this.pagerService = pagerService;

    }    

}

 

com.sterning.books.web.actions.BookAction.java

 

1)、默認情況下,當請求bookAction.action發生時(這個會在後面的Spring配置文件中見到的)Struts運行時(Runtime)根據struts.xml裏的Action映射集(Mapping),實例化com.sterning.books.web.actions.BookAction類,並調用其execute方法。當然,我們可以通過以下兩種方法改變這種默認調用。這個功能(Feature)有點類似Struts 1.x中的LookupDispathAction

 

classes/sturts.xml中新建Action,並指明其調用的方法;

 

訪問Action時,在Action名後加上“!xxx”(xxx爲方法名)。

 

2)、細心的朋友應該可能會發現com.sterning.books.web.actions.BookAction.javaAction方法(execute)返回都是SUCCESS。這個屬性變量我並沒有定義,所以大家應該會猜到它在ActionSupport或其父類中定義。沒錯,SUCCESS在接口com.opensymphony.xwork2.Action中定義,另外同時定義的還有ERROR, INPUT, LOGIN, NONE

 

此外,我在配置Action時都沒有爲result定義名字(name),所以它們默認都爲success。值得一提的是Struts 2.0中的result不僅僅是Struts 1.xforward的別名,它可以實現除forward外的很激動人心的功能,如將Action輸出到FreeMaker模板、Velocity模板、JasperReports和使用XSL轉換等。這些都過result裏的type(類型)屬性(Attribute)定義的。另外,您還可以自定義result類型。

 

3)、使用Struts 2.0,表單數據的輸入將變得非常方便,和普通的POJO一樣在Action編寫GetterSetter,然後在JSPUI標誌的name與其對應,在提交表單到Action時,我們就可以取得其值。

 

4)、Struts 2.0更厲害的是支持更高級的POJO訪問,如this.getBook().getBookPrice()private Books book所引用的是一個關於書的對象類,它可以做爲一個屬性而出現在BookActoin.java類中。這樣對我們開發多層系統尤其有用。它可以使系統結構更清晰。

 

5)、有朋友可能會這樣問:“如果我要取得Servlet API中的一些對象,如requestresponsesession等,應該怎麼做?這裏的execute不像Struts 1.x的那樣在參數中引入。”開發Web應用程序當然免不了跟這些對象打交道。在Strutx 2.0中可以有兩種方式獲得這些對象:非IoC(控制反轉Inversion of Control)方式和IoC方式。

 

IoC方式

 

要獲得上述對象,關鍵是Struts 2.0com.opensymphony.xwork2.ActionContext類。我們可以通過它的靜態方法getContext()獲取當前Action的上下文對象。另外,org.apache.struts2.ServletActionContext作爲輔助類(Helper Class),可以幫助您快捷地獲得這幾個對象。

 

HttpServletRequest request = ServletActionContext.getRequest(); 

 

HttpServletResponse response = ServletActionContext.getResponse(); 

 

HttpSession session = request.getSession();

 

如果你只是想訪問session的屬性(Attribute),你也可以通過ActionContext.getContext().getSession()獲取或添加session範圍(Scoped)的對象。

 

IoC方式

 

要使用IoC方式,我們首先要告訴IoC容器(Container)想取得某個對象的意願,通過實現相應的接口做到這點。如實現SessionAware, ServletRequestAware, ServletResponseAware接口,從而得到上面的對象。

 

1、對BookAction類的Save方法進行驗證

 

正如《Writing Secure Code》文中所寫的名言All input is evil:“所有的輸入都是罪惡的”,所以我們應該對所有的外部輸入進行校驗。而表單是應用程序最簡單的入口,對其傳進來的數據,我們必須進行校驗。Struts2的校驗框架十分簡單方便,只在如下兩步:

 

Xxx-validation.xml文件中的<message>元素中加入key屬性;

 

在相應的jsp文件中的<s:form>標誌中加入validate="true"屬性,就可以在用Javascript在客戶端校驗數據。

 

其驗證文件爲:BooksAction-save-validation.xml

 

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.dtd">

<validators>

    <!-- Field-Validator Syntax -->

    <field name="book.bookName">

        <field-validator type="requiredstring">

            <message key="book.bookName.required"/>

        </field-validator>

    </field>

    <field name="book.bookAuthor">

        <field-validator type="requiredstring">

            <message key="book.bookAuthor.required"/>

        </field-validator>

    </field>

    <field name="book.bookPublish">

        <field-validator type="requiredstring">

            <message key="book.bookPublish.required"/>

        </field-validator>

    </field>

</validators>

 com.sterning.books.web.actions.BooksAction-save-validation.xml 

1、對BookAction類的Save方法進行驗證的資源文件

 

       注意配置文件的名字應該是:配置文件(類名-validation.xml)的格式。BooksAction類的驗證資源文件爲:BooksAction.properties

 

book=Books

book.bookName.required=\u8bf7\u8f93\u5165\u4e66\u540d

book.bookAuthor.required=\u8bf7\u8f93\u5165\u4f5c\u8005

book.bookPublish.required=\u8bf7\u8f93\u5165\u51fa\u7248\u793e

format.date={0,date,yyyy-MM-dd}

 

com.sterning.books.web.actions.BooksAction.properties

 

       資源文件的查找順序是有一定規則的。之所以說Struts 2.0的國際化更靈活是因爲它可以根據不同需要配置和獲取資源(properties)文件。在Struts 2.0中有下面幾種方法:

 

1)、使用全局的資源文件。這適用於遍佈於整個應用程序的國際化字符串,它們在不同的包(package)中被引用,如一些比較共用的出錯提示;

 

2)、使用包範圍內的資源文件。做法是在包的根目錄下新建名的package.propertiespackage_xx_XX.properties文件。這就適用於在包中不同類訪問的資源;

 

3)、使用Action範圍的資源文件。做法爲Action的包下新建文件名(除文件擴展名外)與Action類名同樣的資源文件。它只能在該Action中訪問。如此一來,我們就可以在不同的Action裏使用相同的properties名錶示不同的值。例如,在ActonOnetitle爲“動作一”,而同樣用titleActionTwo表示“動作二”,節省一些命名工夫;

 

4)、使用<s:i18n>標誌訪問特定路徑的properties文件。在使用這一方法時,請注意<s:i18n>標誌的範圍。在<s:i18n name="xxxxx"></s:i18n>之間,所有的國際化字符串都會在名爲xxxxx資源文件查找,如果找不到,Struts 2.0就會輸出默認值(國際化字符串的名字)。

 

例如:某個ChildAction中調用了getText("user.title")Struts 2.0的將會執行以下的操作:

 

查找ChildAction_xx_XX.properties文件或ChildAction.properties

 

查找ChildAction實現的接口,查找與接口同名的資源文件MyInterface.properties

 

查找ChildAction的父類ParentActionproperties文件,文件名爲ParentAction.properties

 

判斷當前ChildAction是否實現接口ModelDriven。如果是,調用getModel()獲得對象,查找與其同名的資源文件;

 

查找當前包下的package.properties文件;

 

查找當前包的父包,直到最頂層包;

 

在值棧(Value Stack)中,查找名爲user的屬性,轉到user類型同名的資源文件,查找鍵爲title的資源

 

查找在struts.properties配置的默認的資源文件,參考例1; 

 

輸出user.title

 

 

七、 Web頁面

 

在這一節中,主要使用到了Struts2的標籤庫。在這裏,會對所用到的主要標籤做一個初步的介紹。更多的知識請讀者訪問Struts的官方網站做更多的學習。在編寫Web頁面之前,先從總體上,對Struts 1.xStruts 2.0的標誌庫(Tag Library)作比較。

 

 Struts 1.x

 Struts 2.0

 

分類

 將標誌庫按功能分成HTMLTilesLogicBean等幾部分

 嚴格上來說,沒有分類,所有標誌都在URI爲“/struts-tags”命名空間下,不過,我們可以從功能上將其分爲兩大類:非UI標誌和UI標誌

 

表達式語言(expression languages

 不支持嵌入語言(EL

 OGNL、JSTLGroovyVelcity

 

1、主頁面:index.jsp,其代碼如下:

 

<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>

<%@ taglib prefix="s" uri="/struts-tags" %>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=GBK"/>

<title>圖書管理系統</title>

</head>

<body>

<p><a href="<s:url action="list" />">進入圖書管理系統</a></p>

</body>

</html>

 

WebRoot/index.jsp

 

要在JSP中使用Struts 2.0標誌,先要指明標誌的引入。通過在JSP的代碼的頂部加入以下代碼可以做到這點。<%@taglib prefix="s" uri="/struts-tags" %>

 

1、<s:url>標籤:該標籤用於創建url,可以通過"param"標籤提供request參數。當includeParams的值時'all'或者'get', param標籤中定義的參數將有優先權,也就是說其會覆蓋其他同名參數的值。

 

2、列表頁面:list.jsp

 

<%@page pageEncoding="gb2312" contentType="text/html; charset=UTF-8" %>

<%@ taglib prefix="s" uri="/struts-tags" %>

 

<html>

<head><title>圖書管理系統</title></head>

    <style type="text/css">

        table {

            border: 1px solid black;

            border-collapse: collapse;

        }

        

        table thead tr th {

            border: 1px solid black;

            padding: 3px;

            background-color: #cccccc;

            background-color: expression(this.rowIndex % 2 == 0 ? "#FFFFFF" : "#EEEEEE");

        }

        

        table tbody tr td {

            border: 1px solid black;

            padding: 3px;

        }

        .trs{

            background-color: expression(this.rowIndex % 2 == 0 ? "#FFFFFF" : "#EEEEEE");

        }

    </style>

 

    <script language="JavaScript">   

        function doSearch(){

            if(document.all.searchValue.value=="")

            {    

                alert("請輸入查詢關鍵字!");

            }else{

                window.location.href="bookAdmin/list.action?queryName="+document.all.searchName.value+"&&queryValue="+document.all.searchValue.value;

             }

        }

    </script>

<body>

 

<table align="center">

<tr align="center">

    <td>

        <select name="searchName">

            <option value="bookName">書名</option>

            <option value="bookAuthor">作者</option>

            <option value="bookPublish">出版社</option>

            <option value="bookDate">出版日期</option>

            <option value="bookIsbn">ISNB</option>

            <option value="bookPage">頁數</option>

        </select>

        <input type="text" name="searchValue" value="" size="10"/>

        <input type="button" value="查詢" onClick="doSearch();">

    </td>

</tr>

<tr align="center">    

    <td>

        <a href="<s:url action="list" includeParams="none"/>">全部</a>

        <a href='<s:url action="edit" ></s:url>'>增加</a>

    </td>

</tr>

<tr>

<td>

<table cellspacing="0" align="center">

    <thead>

    <tr>

        <th>書名</th>

        <th>作者</th>

        <th>出版社</th>

        <th>出版日期</th>

        <th>ISNB</th>

        <th>頁數</th>

        <th>價格</th>

        <th>內容提要</th>

        <th>刪除</th>

    </tr>

    </thead>

    <tbody>

    <s:iterator value="availableItems">

        <tr class="trs">

            <td>

            <a href='<s:url action="edit" ><s:param name="bookId" value="bookId" /></s:url>'>

            <s:property value="bookName"/>

            </a>

            </td>

            <td><s:property value="bookAuthor"/></td>

            <td><s:property value="bookPublish"/></td>

            <td><s:text name="format.date"><s:param value="bookDate"/></s:text></td>     

            <td><s:property value="bookIsbn" /></td>

            <td><s:property value="bookPage" /></td>

            <td><s:property value="bookPrice"/></td>

            <td><s:property value="bookContent"/></td>

            

            <td><a href='<s:url action="delete"><s:param name="bookId" value="bookId" /></s:url>'>刪除</a></td>

        </tr>

    </s:iterator>

    <tr align="right">

        <td colspan="9">

            共<s:property value="totalRows"/> 

            第<s:property value="currentPage"/> 

            共<s:property value="pager.getTotalPages()"/> 

            <a href="<s:url value="list.action">

                <s:param name="currentPage" value="currentPage"/>

                <s:param name="pagerMethod" value="'first'"/>

                

            </s:url>">首頁</a>

            <a href="<s:url value="list.action">

                <s:param name="currentPage" value="currentPage"/>

                <s:param name="pagerMethod" value="'previous'"/>

            </s:url>">上一頁</a>

            <a href="<s:url value="list.action">

                <s:param name="currentPage" value="currentPage"/>

                <s:param name="pagerMethod" value="'next'"/>

            </s:url>">下一頁</a>

            <a href="<s:url value="list.action">

                <s:param name="currentPage" value="currentPage"/>

                <s:param name="pagerMethod" value="'last'"/>

            </s:url>">尾頁</a>

        </td>

    </tr>    

    </tbody>

</table>

</td>

</tr>

</table>

</body>

</html>

 

/WebRoot/list.jsp

 

(1)、<s:property> :得到'value'的屬性,如果value沒提供,默認爲堆棧頂端的元素。其相關的參數及使用如下表所示:

 

名稱

 必需

 默認

 類型

 描述

 

default

 否

  String

 如果屬性是null則顯示的default

 

escape

 否

 true

 Booelean

 是否escape HTML

 

value

 否

 棧頂

 Object

 要顯示的值

 

id

 否

  Object/String

 用來標識元素的id。在UI和表單中爲HTMLid屬性

 

 

(2)、<s:Iterator>:用於遍歷集合(java.util.Collection)或枚舉值(java.util.Iterator)。其相關的參數及使用如下表所示:  

 

名稱

 必需

 默認

 類型

 描述

 

status

 否

  String

 如果設置此參數,一個IteratorStatus的實例將會壓入每個遍歷的堆棧

 

value

 否

  Object/String

 要遍歷的可枚舉的(iteratable)數據源,或者將放入新列表(List)的對象

 

id

 否

  Object/String

 用來標識元素的id。在UI和表單中爲HTMLid屬性

 

 

(3)、<s:param>:爲其他標籤提供參數,比如include標籤和bean標籤參數的name屬性是可選的,如果提供,會調用Component的方法addParameter(String, Object), 如果不提供,則外層嵌套標籤必須實現UnnamedParametric接口(TextTag)。 value的提供有兩種方式,通過value屬性或者標籤中間的text,不同之處我們看一下例子:

 

<param name="color">blue</param><!-- (A) -->

 

<param name="color" value="blue"/><!-- (B) -->

(A)參數值會以String的格式放入statck. 

(B)該值會以java.lang.Object的格式放入statck.

 

其相關的參數及使用如下表所示:

 

名稱

 必需

 默認

 類型

 描述

 

name

 否

  String

 參數名

 

value

 否

  String

 value表達式

 

id

 否

  Object/String

 用來標識元素的id。在UI和表單中爲HTMLid屬性

 

 

4)、國際化是商業系統中不可或缺的一部分,所以無論您學習的是什麼Web框架,它都是必須掌握的技能。其實,Struts 1.x在此部分已經做得相當不錯了。它極大地簡化了我們程序員在做國際化時所需的工作,例如,如果您要輸出一條國際化的信息,只需在代碼包中加入FILE-NAME_xx_XX.properties(其中FILE-NAME爲默認資源文件的文件名),然後在struts-config.xml中指明其路徑,再在頁面用<bean:message>標誌輸出即可。

 

不過,所謂“沒有最好,只有更好”。Struts 2.0並沒有在這部分止步,而是在原有的簡單易用的基礎上,將其做得更靈活、更強大。

 

5)、list.jsp文件中:

 

<s:text name="format.date"><s:param value="bookDate"/></s:text>,爲了正確的輸出出版日期的格式,採用在資源文件中定義輸出的格式,並在頁面上調用。format.date就是在資源文件com.sterning.books.web.actions.BooksAction.properties中定義。當然也可以別的文件,放在別的路徑下,但此時需要在web.xml中註冊纔可以使用它。

 

正如讀者所見,在pojo(本例爲Books.java)中將日期字段設置爲java.util.Date,在映射文件中(books.hbm.xml)設置爲timestamp(包括日期和時間)。爲了便於管理,將日期格式保存在國際化資源文件中。如:globalMessagesglobalMessages_zh_CN文件。

 

其內容爲:

 

format.date={0,date,yyyy-MM-dd}

 

在頁面顯示日期時間時:<s:text name="format.date"><s:param value="bookDate"/></s:text>。這樣就解決了日期(時間)的顯示格式化問題。

 

3、增加/修改頁面:editBook.jsp  

 

<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>

<%@ taglib prefix="s" uri="/struts-tags" %>

 

<html>

<head>

    <title>編輯圖書</title>

    <s:head/>

</head>

<body>

    <h2>

        <s:if test="null == book">

            增加圖書

        </s:if>

        <s:else>

            編輯圖書

        </s:else>

    </h2>

    <s:form name="editForm" action="save" validate="true">

    

         <s:textfield label="書名" name="book.bookName"/>

         <s:textfield label="作者" name="book.bookAuthor"/>

         <s:textfield label="出版社" name="book.bookPublish"/>

         <s:datetimepicker label="出版日期" name="book.bookDate"></s:datetimepicker>

         <s:textfield label="ISBN" name="book.bookIsbn"/>

         <s:textfield label="頁數" name="book.bookPage"/>

         <s:textfield label="價格()" name="book.bookPrice"/>

         <s:textfield label="內容摘要" name="book.bookContent"/>

         <s:if test="null == book">

             <s:hidden name="book.bookId" value="%{bookId}"/>

         </s:if>         

         <s:else>

             <s:hidden name="book.bookId" />

         </s:else>

         <s:hidden name="queryName" />

         <s:hidden name="queryValue" />

         <s:submit value="%{getText('保存')}" />

    </s:form>

 

<p><a href="<s:url action="list"/>">返回</a></p>

</body>

</html>

 

 

WebRoot/editBook.jsp

 

1)、<s:if><s:elseif><s:else> :執行基本的條件流轉。 其相關的參數及使用如下表所示:

 

名稱

 必需

 默認

 類型

 描述

 備註

 

test

 是

  

 Boolean

 決定標誌裏內容是否顯示的表達式

 else標誌沒有這個參數

 

id

 否

  

 Object/String

 用來標識元素的id。在UI和表單中爲HTMLid屬性

  

 

2)、<s:text>:支持國際化信息的標籤。國際化信息必須放在一個和當前action同名的resource bundle,如果沒有找到相應message,tag body將被當作默認message,如果沒有tag body,messagename會被作爲默認message。 其相關的參數及使用如下表所示:

 

名稱

 必需

 默認

 類型

 描述

 

name

 是

  

 String

 資源屬性的名字

 

id

 否

  

 Object/String

 用來標識元素的id。在UI和表單中爲HTMLid屬性 

 

八、  配置Struts2

 

 

Struts的配置文件都會在web.xml中註冊的。

 

a)   Struts的配置文件如下:

 

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC

    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

    "http://struts.apache.org/dtds/struts-2.0.dtd">

 

<struts>

 

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />

    <constant name="struts.devMode" value="true" />

    <constant name="struts.i18n.encoding" value="GBK" />   

 

    <!-- Add packages here -->

 

</struts>

 

Src/struts.xml

 

b)   struts_book.xml配置文件如下:

 

 

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC

        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

        "http://struts.apache.org/dtds/struts-2.0.dtd">

 

<struts>

 

    <package name="products" extends="struts-default">

        <!--default-interceptor-ref name="validation"/-->

         <!-- Add actions here -->

        <action name="list" class="bookAction" method="list">            

            <result>/list.jsp</result>

        </action>

 

    <action name="delete" class="bookAction" method="delete">            

            <result type="redirect">list.action?queryMap=${queryMap}</result>

        </action>

 

        <action name="*" class="com.sterning.commons.AbstractAction">

            <result>/{1}.jsp</result>

        </action>

        

    <action name="edit" class="bookAction" method="load">

            <result>/editBook.jsp</result>

        </action>

       

       <action name="save" class="bookAction" method="save">

           <interceptor-ref name="params"/>

           <interceptor-ref name="validation"/>

            <result name="input">/editBook.jsp</result>

            <result type="redirect">list.action?queryMap=${queryMap}</result>

              

        </action>

    </package>

</struts>

文件中的<interceptor-ref name="params"/>,使用了struts2自己的攔截器,攔截器在AOPAspect-Oriented Programming)中用於在某個方法或字段被訪問之前,進行攔截然後在之前或之後加入某些操作。攔截是AOP的一種實現策略。

 

Struts 2已經提供了豐富多樣的,功能齊全的攔截器實現。大家可以到struts2-all-2.0.6.jarstruts2-core-2.0.6.jar包的struts-default.xml查看關於默認的攔截器與攔截器鏈的配置。

 

struts-default.xml中已經配置了大量的攔截器。如果您想要使用這些已有的攔截器,只需要在應用程序struts.xml文件中通過“<include file="struts-default.xml" />”將struts-default.xml文件包含進來,並繼承其中的struts-default包(package),最後在定義Action時,使用“<interceptor-ref name="xx" />”引用攔截器或攔截器棧(interceptor stack)。一旦您繼承了struts-default包(package),所有Action都會調用攔截器棧 ——defaultStack。當然,在Action配置中加入“<interceptor-ref name="xx" />”可以覆蓋defaultStack

 

作爲“框架(framework)”,可擴展性是不可或缺的,因爲世上沒有放之四海而皆準的東西。雖然,Struts 2爲我們提供如此豐富的攔截器實現,但是這並不意味我們失去創建自定義攔截器的能力,恰恰相反,在Struts 2自定義攔截器是相當容易的一件事。所有的Struts 2的攔截器都直接或間接實現接口com.opensymphony.xwork2.interceptor.Interceptor。除此之外,大家可能更喜歡繼承類com.opensymphony.xwork2.interceptor.AbstractInterceptor

 

九、 配置Spring

 

 

1、Spring的配置文件如下:

 

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

 

<beans>

    <!-- dataSource config -->

    <bean id ="dataSource" class ="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> 

        <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 

        <property name="url" value="jdbc:mysql://localhost:3306/game" /> 

        <property name="username" value="root" /> 

        <property name="password" value="root"/> 

    </bean> 

    

    <!-- SessionFactory -->

    <bean id="sessionFactory"

        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

 

        <property name="dataSource">

            <ref bean="dataSource"/>

        </property>

        <property name="configLocation">

            <value>classpath:com\sterning\bean\hibernate\hibernate.cfg.xml</value>

        </property>        

    </bean>

    

    <!-- TransactionManager  不過這裏暫時沒注入-->

    <bean id="transactionManager"

        class="org.springframework.orm.hibernate3.HibernateTransactionManager">

        <property name="sessionFactory">

            <ref local="sessionFactory"/>

        </property>

    </bean>

    

    <!-- DAO -->

    <bean id="booksDao" class="com.sterning.books.dao.hibernate.BooksMapDao">

        <property name="sessionFactory">

            <ref bean="sessionFactory"/>

        </property>

    </bean>

    

    <!-- Services -->

    <bean id="booksService" class="com.sterning.books.services.BooksService">

        <property name="booksDao">

            <ref bean="booksDao"/>

        </property>

    </bean>

    

    <bean id="pagerService" class="com.sterning.commons.PagerService"/>

    

    <!-- view -->

    <bean id="bookAction" class="com.sterning.books.web.actions.BooksAction" singleton="false">

        <property name="booksService">

            <ref bean="booksService"/>

        </property>

        <property name="pagerService">

            <ref bean="pagerService"/>

        </property>

    </bean>  

    

</beans>

 

  WebRoot/WEB-INF/srping-content/applicationContent.xml 

2、Struts.properties.xml

 

本來此文件應該寫在struts 配置一節,但主要是考慮這體現了集成spring的配置,所以放在spring的配置這裏來講。

 

struts.objectFactory = spring  

struts.locale=zh_CN

struts.i18n.encoding = GBK

struts.objectFacto:ObjectFactory 實現了 com.opensymphony.xwork2.ObjectFactory接口(spring)。struts.objectFactory=spring,主要是告知Struts 2運行時使用Spring來創建對象(如Action等)。當然,SpringContextLoaderListener監聽器,會在web.xml文件中編寫,負責SpringWeb容器交互。

struts.locale:The default locale for the Struts application。 默認的國際化地區信息。

struts.i18n.encoding:國際化信息內碼。

 

十、Web.xml配置

 

 

<?xml version="1.0" encoding="GB2312"?>

<!DOCTYPE web-app

    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

    "http://java.sun.com/dtd/web-app_2_3.dtd">

 

<web-app>

    <display-name>圖書管理系統</display-name>

    <context-param>

        <param-name>log4jConfigLocation</param-name>

        <param-value>/WEB-INF/classes/log4j.properties</param-value>

    </context-param>

    <!-- ContextConfigLocation -->

    <context-param>

        <param-name>contextConfigLocation</param-name>

        <param-value>/WEB-INF/spring-context/applicationContext.xml</param-value>

      </context-param>

    

    <filter>

        <filter-name>encodingFilter</filter-name>

        <filter-class>com.sterning.commons.SetCharacterEncodingFilter</filter-class>

        <init-param>

            <param-name>encoding</param-name>

            <param-value>UTF-8</param-value>

        </init-param>

        <init-param>

            <param-name>forceEncoding</param-name>

            <param-value>true</param-value>

        </init-param>

    </filter>

     <filter>

        <filter-name>struts2</filter-name>

        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>

        <init-param>

            <param-name>config</param-name>

            <param-value>struts-default.xml,struts-plugin.xml,struts.xml,struts_books.xml</param-value>

        </init-param>

    </filter>    

 

    <filter-mapping>

        <filter-name>encodingFilter</filter-name>

        <url-pattern>/*</url-pattern>

    </filter-mapping>

    <filter-mapping>

        <filter-name>struts2</filter-name>

        <url-pattern>/*</url-pattern>

    </filter-mapping>        

    

    <!-- Listener contextConfigLocation -->

      <listener>

        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

      </listener>

    <!-- Listener log4jConfigLocation -->

      <listener>

        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>

      </listener>

 

    <!-- The Welcome File List -->

    <welcome-file-list>

        <welcome-file>index.jsp</welcome-file>

    </welcome-file-list>

</web-app>

 

 

public void setQueryName(String queryName) {

this.queryName = queryName;

}

public String getQueryValue() {

return queryValue;

}

public void setQueryValue(String queryValue) {

this.queryValue = queryValue;

}

public String getSearchName() {

return searchName;

}

public void setSearchName(String searchName) {

this.searchName = searchName;

}

public String getSearchValue() {

return searchValue;

}

public void setSearchValue(String searchValue) {

this.searchValue = searchValue;

}

public String getQueryMap() {

return queryMap;

}

public void setQueryMap(String queryMap) {

this.queryMap = queryMap;

}

public PagerService getPagerService() {

return pagerService;

}

public void setPagerService(PagerService pagerService) {

this.pagerService = pagerService;

}

}

 

com.sterning.books.web.actions.BookAction.java

 

 

1)、默認情況下,當請求bookAction.action發生時(這個會在後面的Spring配置文件中見到的)Struts運行時(Runtime)根據struts.xml裏的Action映射集(Mapping),實例化com.sterning.books.web.actions.BookAction類,並調用其execute方法。當然,我們可以通過以下兩種方法改變這種默認調用。這個功能(Feature)有點類似Struts 1.x中的LookupDispathAction

 

classes/sturts.xml中新建Action,並指明其調用的方法;

訪問Action時,在Action名後加上“!xxx”(xxx爲方法名)。

 

2)、細心的朋友應該可能會發現com.sterning.books.web.actions.BookAction.javaAction方法(execute)返回都是SUCCESS。這個屬性變量我並沒有定義,所以大家應該會猜到它在ActionSupport或其父類中定義。沒錯,SUCCESS在接口com.opensymphony.xwork2.Action中定義,另外同時定義的還有ERROR, INPUT, LOGIN, NONE

 

此外,我在配置Action時都沒有爲result定義名字(name),所以它們默認都爲success。值得一提的是Struts 2.0中的result不僅僅是Struts 1.xforward的別名,它可以實現除forward外的很激動人心的功能,如將Action輸出到FreeMaker模板、Velocity模板、JasperReports和使用XSL轉換等。這些都過result裏的type(類型)屬性(Attribute)定義的。另外,您還可以自定義result類型。

 

3)、使用Struts 2.0,表單數據的輸入將變得非常方便,和普通的POJO一樣在Action編寫GetterSetter,然後在JSPUI標誌的name與其對應,在提交表單到Action時,我們就可以取得其值。

 

4)、Struts 2.0更厲害的是支持更高級的POJO訪問,如this.getBook().getBookPrice()private Books book所引用的是一個關於書的對象類,它可以做爲一個屬性而出現在BookActoin.java類中。這樣對我們開發多層系統尤其有用。它可以使系統結構更清晰。

5)、有朋友可能會這樣問:“如果我要取得Servlet API中的一些對象,如requestresponsesession等,應該怎麼做?這裏的execute不像Struts 1.x的那樣在參數中引入。”開發Web應用程序當然免不了跟這些對象打交道。在Strutx 2.0中可以有兩種方式獲得這些對象:非IoC(控制反轉Inversion of Control)方式和IoC方式。

 

<!--EndFragment-->

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章