Struts2和Spring和Hibernate應用實例

Struts2、Spring和Hibernate應用實例
Struts作為MVC 2的Web框架,自推出以來不斷受到開發者的追捧,得到廣泛的應用。作為最成功的Web框架,Struts自然擁有眾多的優點:MVC 2模型的使用、功能齊全的標志庫(Tag Library)、開放源代碼。而Spring的出現,在某些方面極大的方面了Struts的開發。同時,Hibernate作為對象持久化的框架,能顯示的提高軟件開發的效率與生產力。這三種流行框架的整合應用,可以發揮它們各自的優勢,使軟件開發更加的快速與便捷。
struts2發布已經很久了,但關于如何使用它的教程及實例并不多。特別是與Spring及Hibernate等流行框架的集成,并不多見。現在就將筆者使用Myeclipse工具應用struts2 + spring2 + hibernate3 實現CRUD操作的步驟一一紀錄下來,為初學者少走彎路略盡綿薄之力!在本文中,筆者將Struts2.0.6、Spring2.0.6和Hibernate3.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中,通過Getter和Setter獲取。
雖然,在理論上Struts2的Action無須實現任何接口或者是繼承任何的類,但是,在實際編程過程中,為了更加方便的實現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、編寫實體類Books及books.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();
}
});
}
}
五、業務邏輯層
在業務邏輯層需要認真思考每個業務邏輯所能用到的持久層對象和DAO。DAO層之上是業務邏輯層,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經驗的朋友都知道Action是Struts的核心內容,當然Struts 2.0也不例外。不過,Struts 1.x與Struts 2.0的Action模型很大的區別。
Struts 1.x
Stuts 2.0

接口
必須繼承org.apache.struts.action.Action或者其子類
無須繼承任何類型或實現任何接口
表單數據
表單數據封裝在FormBean中
表單數據包含在Action中,通過Getter和Setter獲取
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.java中Action方法(execute)返回都是SUCCESS。這個屬性變量我并沒有定義,所以大家應該會猜到它在ActionSupport或其父類中定義。沒錯,SUCCESS在接口com.opensymphony.xwork2.Action中定義,另外同時定義的還有ERROR, INPUT, LOGIN, NONE。
此外,我在配置Action時都沒有為result定義名字(name),所以它們默認都為success。值得一提的是Struts 2.0中的result不僅僅是Struts 1.x中forward的別名,它可以實現除forward外的很激動人心的功能,如將Action輸出到FreeMaker模板、Velocity模板、JasperReports和使用XSL轉換等。這些都過result里的type(類型)屬性(Attribute)定義的。另外,您還可以自定義result類型。
(3)、使用Struts 2.0,表單數據的輸入將變得非常方便,和普通的POJO一樣在Action編寫Getter和Setter,然后在JSP的UI標志的name與其對應,在提交表單到Action時,我們就可以取得其值。
(4)、Struts 2.0更厲害的是支持更高級的POJO訪問,如this.getBook().getBookPrice()。private Books book所引用的是一個關于書的對象類,它可以做為一個屬性而出現在BookActoin.java類中。這樣對我們開發多層系統尤其有用。它可以使系統結構更清晰。
(5)、有朋友可能會這樣問:“如果我要取得Servlet API中的一些對象,如request、response或session等,應該怎么做?這里的execute不像Struts 1.x的那樣在參數中引入。”開發Web應用程序當然免不了跟這些對象打交道。在Strutx 2.0中可以有兩種方式獲得這些對象:非IoC(控制反轉Inversion of Control)方式和IoC方式。
非IoC方式
要獲得上述對象,關鍵是Struts 2.0中com.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.properties和package_xx_XX.properties文件。這就適用于在包中不同類訪問的資源;

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

(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的父類ParentAction的properties文件,文件名為ParentAction.properties;

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

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

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

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

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

輸出user.title。

七、 Web頁面

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


Struts 1.x
Struts 2.0

分類
將標志庫按功能分成HTML、Tiles、Logic和Bean等幾部分
嚴格上來說,沒有分類,所有標志都在URI為“/struts-tags”命名空間下,不過,我們可以從功能上將其分為兩大類:非UI標志和UI標志

表達式語言(expression languages)
不支持嵌入語言(EL)
OGNL、JSTL、Groovy和Velcity

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和表單中為HTML的id屬性


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

名稱
必需
默認
類型
描述

status

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

value

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

id

Object/String
用來標識元素的id。在UI和表單中為HTML的id屬性


(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和表單中為HTML的id屬性


(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(包括日期和時間)。為了便于管理,將日期格式保存在國際化資源文件中。如:globalMessages或globalMessages_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和表單中為HTML的id屬性


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

名稱
必需
默認
類型
描述

name


String
資源屬性的名字

id


Object/String
用來標識元素的id。在UI和表單中為HTML的id屬性

八、 配置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自己的攔截器,攔截器在AOP(Aspect-Oriented Programming)中用于在某個方法或字段被訪問之前,進行攔截然后在之前或之后加入某些操作。攔截是AOP的一種實現策略。

Struts 2已經提供了豐富多樣的,功能齊全的攔截器實現。大家可以到struts2-all-2.0.6.jar或struts2-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等)。當然,Spring的ContextLoaderListener監聽器,會在web.xml文件中編寫,負責Spring與Web容器交互。
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.java中Action方法(execute)返回都是SUCCESS。這個屬性變量我并沒有定義,所以大家應該會猜到它在ActionSupport或其父類中定義。沒錯,SUCCESS在接口com.opensymphony.xwork2.Action中定義,另外同時定義的還有ERROR, INPUT, LOGIN, NONE。

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

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

(4)、Struts 2.0更厲害的是支持更高級的POJO訪問,如this.getBook().getBookPrice()。private Books book所引用的是一個關于書的對象類,它可以做為一個屬性而出現在BookActoin.java類中。這樣對我們開發多層系統尤其有用。它可以使系統結構更清晰。
(5)、有朋友可能會這樣問:“如果我要取得Servlet API中的一些對象,如request、response或session等,應該怎么做?這里的execute不像Struts 1.x的那樣在參數中引入。”開發Web應用程序當然免不了跟這些對象打交道。在Strutx 2.0中可以有兩種方式獲得這些對象:非IoC(控制反轉Inversion of Control)方式和IoC方式。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/444359.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/444359.shtml
英文地址,請注明出處:http://en.pswp.cn/news/444359.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

C++(STL):31 ---關聯式容器map源碼剖析

map的特性 所有元素都會根據元素的鍵值自動被排序map中的pair結構 map的所有元素類型都是pair,同時擁有實值(value)和鍵值(key)pair的第一個元素視為鍵值,第二個元素視為實值map不允許兩個元素擁有相同的鍵值下面是stl_pair.h中pair的定義://代碼摘錄與stl_pair.htempla…

leetcode360. 有序轉化數組

給你一個已經 排好序 的整數數組 nums 和整數 a、b、c。對于數組中的每一個數 x&#xff0c;計算函數值 f(x) ax2 bx c&#xff0c;請將函數值產生的數組返回。 要注意&#xff0c;返回的這個數組必須按照 升序排列&#xff0c;并且我們所期望的解法時間復雜度為 O(n)。 示…

C++(STL):27 ---關聯式容器set源碼剖析

一、set set語法使用參閱:set的特性 set所有元素都會根據元素的鍵值自動被排序set中的鍵值就是實值,實值就是鍵值默認情況下set不允許兩個元素重復set的迭代器 不能根據set的迭代器改變set元素的值。因為其鍵值就是實值,實值就是鍵值,如果改變set元素值,會嚴重破壞set組織…

C++(STL):28 ---關聯式容器map用法

作為關聯式容器的一種,map 容器存儲的都是 pair 對象,也就是用 pair 類模板創建的鍵值對。其中,各個鍵值對的鍵和值可以是任意數據類型,包括 C++ 基本數據類型(int、double 等)、使用結構體或類自定義的類型。 通常情況下,map 容器中存儲的各個鍵值對都選用 string 字符…

C++(STL):26 ---關聯式容器set用法

set容器都會自行根據鍵的大小對存儲的鍵值對進行排序, 只不過 set 容器中各鍵值對的鍵 key 和值 value 是相等的,根據 key 排序,也就等價為根據 value 排序。 另外,使用 set 容器存儲的各個元素的值必須各不相同。更重要的是,從語法上講 set 容器并沒有強制對存儲元素的類…

leetcode387. 字符串中的第一個唯一字符

給定一個字符串&#xff0c;找到它的第一個不重復的字符&#xff0c;并返回它的索引。如果不存在&#xff0c;則返回 -1。 案例: s "leetcode" 返回 0. s "loveleetcode", 返回 2. 注意事項&#xff1a;您可以假定該字符串只包含小寫字母。 思路&…

C++(STL):30 ---關聯式容器map的operator[]和insert效率對比

通過前面的學習我們知道,map 容器模板類中提供有 operator[ ] 和 insert() 這 2 個成員方法,而值得一提的是,這 2 個方法具有相同的功能,它們既可以實現向 map 容器中添加新的鍵值對元素,也可以實現更新(修改)map 容器已存儲鍵值對的值。舉個例子(程序一): #include …

C++(STL):29 ---關聯式容器map 迭代器

無論是前面學習的序列式容器,還是關聯式容器,要想實現遍歷操作,就必須要用到該類型容器的迭代器。當然,map 容器也不例外。C++ STL 標準庫為 map 容器配備的是雙向迭代器(bidirectional iterator)。這意味著,map 容器迭代器只能進行 ++p、p++、--p、p--、*p 操作,并且迭…

C++(STL):35---multimap容器

在掌握 C++ STL map 容器的基礎上,本節再講一個和 map 相似的關聯式容器,即 multimap 容器。所謂“相似”,指的是 multimap 容器具有和 map 相同的特性,即 multimap 容器也用于存儲 pair<const K, T> 類型的鍵值對(其中 K 表示鍵的類型,T 表示值的類型),其中各個…

在Spring + Hibernate中使用二級緩存配置步驟

在SSH中用二級緩存大概分以下幾步&#xff1a; 1、首先在hbm文件里對涉及到的對象設置緩存方式&#xff0c;或根據情況設置自己需要的 2、在ehcache的配置文件里配置一個cache&#xff0c;name為這個類名 3、在applicationContext.xml的hibernate配置里 hibernate.cache.use_q…

C++(STL):34--- multiset容器詳解

前面章節中,對 set 容器做了詳細的講解。回憶一下,set 容器具有以下幾個特性: 不再以鍵值對的方式存儲數據,因為 set 容器專門用于存儲鍵和值相等的鍵值對,因此該容器中真正存儲的是各個鍵值對的值(value);set 容器在存儲數據時,會根據各元素值的大小對存儲的元素進行…

C++(STL):36---關聯式容器multiset、multimap源碼剖析

一、multiset multiset的特性以及用法和set完全相同,唯一的差別在于它允許鍵值重復,因此它的插入操作采用的是底層RB-tree的insert_equal()而非insert_unique() multiset源碼 //以下代碼摘錄于stl_multiset.htemplate <class _Key, class _Compare, class _Alloc>clas…

leetcode 455. 分發餅干

假設你是一位很棒的家長&#xff0c;想要給你的孩子們一些小餅干。但是&#xff0c;每個孩子最多只能給一塊餅干。對每個孩子 i &#xff0c;都有一個胃口值 gi &#xff0c;這是能讓孩子們滿足胃口的餅干的最小尺寸&#xff1b;并且每塊餅干 j &#xff0c;都有一個尺寸 sj 。…

C++(STL):33---hash_set、hash_map、hash_multiset、hash_multimap源碼剖析

這些關聯容器底層都是使用hash table實現的.一、hash_set 由于hash_set底層是以hash table實現的,因此hash_set只是簡單的調用hash table的方法即可與set的異同點:hash_set與set都是用來快速查找元素的但是set會對元素自動排序,而hash_set沒有hash_set和set的使用方法相同在…

leetcode402. 移掉K位數字

給定一個以字符串表示的非負整數 num&#xff0c;移除這個數中的 k 位數字&#xff0c;使得剩下的數字最小。 注意: num 的長度小于 10002 且 ≥ k。 num 不會包含任何前導零。 示例 1 : 輸入: num "1432219", k 3 輸出: "1219" 解釋: 移除掉三個數字…

C++:43---派生類向基類轉換、靜態/動態的類變量

一、繼承中類的類型轉換規則 我們普通的編程規則規定,如果我們想把引用或指針綁定到一個對象上,則引用或指針的類型必須與所綁定的對象的類型一致或者對象的類型含有一種可接受的const類型轉換規則。但是繼承關系中的類比較例外,其規則如下:①我們可以將基類的指針或引用綁…

C++:42---類的內存大小

一、類內存的特點 類內無任何成員變量時,默認為1字節類內成員遵循內存的對齊補齊規則(與結構體的對齊補齊一樣)函數不占內存(存在代碼段)有繼承關系時,父類的成員變量也屬于類內寸的一部分,但是C++標準并沒有明確規定派生類的對象在內存中如何分布(也就是說基類部分和派…

C++:40---繼承中類成員的變化關系

一、派生類繼承基類成員的規則 ①派生類繼承了基類的所有數據成員與函數(不論公有成員、保護成員、私有成員)②派生類雖然繼承了基類的所有成員,但是能不能訪問基類的成員還與父類成員的屬性(public、protected、private)以及繼承方式有關③類靜態成員:如果基類定義了一個靜…

C++:37---繼承概念、繼承種類

這篇文章不詳細分析繼承和不同繼承關系下的特點。 我將在后邊幾篇文章里專門針對繼承關系來做分析。 一、基類與派生類的概念 基類(父類):在繼承關系中處于上層的類派生類(子類):在繼承關系中處于下層的類class A;class B;class C:public A //C為A的子類,A為C的父類{};…

C++:41---覆蓋和隱藏

覆蓋(重寫) 概念: 基類的虛函數,如果派生類有相同的函數,則子類的方法覆蓋了父類的方法 隱藏 概念: 當子類定義出的“成員變量、方法”與父類的重名時,父類的會被隱藏重點:對于函數,基類定義了一些列的重載函數,在派生類中只要有一個同名的函數(即使參數列表不…