您的位置:首页 > 编程语言 > Java开发

Struts2、Spring和Hibernate应用实例(中)

2014-10-22 01:11 435 查看
Struts2、Spring和Hibernate应用实例四、建立DAO

DAO访问层负责封装底层的数据访问细节,不仅可以使概念清晰,而且可以提高开发效率。
1、建立DAO的接口类:BooksDao

packagecom.sterning.books.dao.iface;
importjava.util.List;
importcom.sterning.books.model.Books;
publicinterface BooksDao {
ListgetAll();//获得所有记录
List getBooks(int pageSize, intstartRow);//获得所有记录
int getRows();//获得总行数
int getRows(String fieldname,Stringvalue);//获得总行数
List queryBooks(String fieldname,Stringvalue);//根据条件查询
List getBooks(String fieldname,Stringvalue,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

packagecom.sterning.books.dao.hibernate;
importjava.sql.SQLException;
importjava.util.Iterator;
importjava.util.List;
importorg.hibernate.HibernateException;
importorg.hibernate.Query;
importorg.hibernate.Session;
importorg.springframework.orm.hibernate3.HibernateCallback;
importorg.springframework.orm.hibernate3.support.HibernateDaoSupport;
importcom.sterning.books.dao.iface.BooksDao;
importcom.sterning.books.model.Books;
importcom.sterning.commons.PublicUtil;
/**
*@author cwf
*
*/
publicclass BooksMapDao extends HibernateDaoSupport implements BooksDao {
publicBooksMapDao(){}
/**
* 函数说明:添加信息
* 参数说明:对象
* 返回值:
*/
public void addBook(Books book) {
this.getHibernateTemplate().save(book);
}
/**
* 函数说明:删除信息
* 参数说明:对象
* 返回值:
*/
public void deleteBook(Books book) {
this.getHibernateTemplate().delete(book);
}
/**
* 函数说明:获得所有的信息
* 参数说明:
* 返回值:信息的集合
*/
public List getAll() {
Stringsql="FROM Books ORDER BY bookName";
returnthis.getHibernateTemplate().find(sql);
}
/**
* 函数说明:获得总行数
* 参数说明:
* 返回值:总行数
*/
public int getRows() {
Stringsql="FROM Books ORDER BY bookName";
Listlist=this.getHibernateTemplate().find(sql);
returnlist.size();
}
/**
* 函数说明:获得所有的信息
* 参数说明:
* 返回值:信息的集合
*/
public List getBooks(int pageSize, intstartRow) throws HibernateException {
finalint pageSize1=pageSize;
finalint startRow1=startRow;
returnthis.getHibernateTemplate().executeFind(new HibernateCallback(){
publicList doInHibernate(Session session) throws HibernateException, SQLException {
//TODO 自动生成方法存根
Queryquery=session.createQuery("FROM Books ORDER BY bookName");
query.setFirstResult(startRow1);
query.setMaxResults(pageSize1);
returnquery.list();
}
});
}
/**
* 函数说明:获得一条的信息
* 参数说明: ID
* 返回值:对象
*/
public Books getBook(String bookId) {
return(Books)this.getHibernateTemplate().get(Books.class,bookId);
}
/**
* 函数说明:获得最大ID
* 参数说明:
* 返回值:最大ID
*/
public String getMaxID() {
Stringdate=PublicUtil.getStrNowDate();
Stringsql="SELECT MAX(bookId)+1 FROM Books ";
StringnoStr = null;
Listll = (List) this.getHibernateTemplate().find(sql);
Iteratoritr = ll.iterator();
if(itr.hasNext()) {
Objectnoint = itr.next();
if(noint== null){
noStr= "1";
}else{
noStr= noint.toString();
}
}
if(noStr.length()==1){
noStr="000"+noStr;
}elseif(noStr.length()==2){
noStr="00"+noStr;
}elseif(noStr.length()==3){
noStr="0"+noStr;
}else{
noStr=noStr;
}
returnnoStr;
}
/**
* 函数说明:修改信息
* 参数说明:对象
* 返回值:
*/
public void updateBook(Books pd) {
this.getHibernateTemplate().update(pd);
}
/**
* 函数说明:查询信息
* 参数说明:集合
* 返回值:
*/
public List queryBooks(Stringfieldname,String value) {
System.out.println("value:"+value);
Stringsql="FROM Books where "+fieldname+" like'%"+value+"%'"+"ORDER BY bookName";
returnthis.getHibernateTemplate().find(sql);
}
/**
* 函数说明:获得总行数
* 参数说明:
* 返回值:总行数
*/
public int getRows(String fieldname,Stringvalue) {
Stringsql="";
if(fieldname==null||fieldname.equals("")||fieldname==null||fieldname.equals(""))
sql="FROMBooks ORDER BY bookName";
else
sql="FROMBooks where "+fieldname+" like'%"+value+"%'"+"ORDER BY bookName";
Listlist=this.getHibernateTemplate().find(sql);
returnlist.size();
}
/**
* 函数说明:查询信息
* 参数说明:集合
* 返回值:
*/

publicList getBooks(String fieldname,String value,int pageSize, int startRow) {
finalint pageSize1=pageSize;
finalint startRow1=startRow;
finalString queryName=fieldname;
finalString queryValue=value;
Stringsql="";
if(queryName==null||queryName.equals("")||queryValue==null||queryValue.equals(""))
sql="FROMBooks ORDER BY bookName";
else
sql="FROMBooks where "+fieldname+" like'%"+value+"%'"+"ORDER BY bookName";
finalString sql1=sql;
returnthis.getHibernateTemplate().executeFind(new HibernateCallback(){
publicList doInHibernate(Session session) throws HibernateException, SQLException {
//TODO 自动生成方法存根
Queryquery=session.createQuery(sql1);
query.setFirstResult(startRow1);
query.setMaxResults(pageSize1);
returnquery.list();
}
});
}
}
五、业务逻辑层

在业务逻辑层需要认真思考每个业务逻辑所能用到的持久层对象和DAO。DAO层之上是业务逻辑层,DAO类可以有很多个,但业务逻辑类应该只有一个,可以在业务逻辑类中调用各个DAO类进行操作。
1、创建服务接口类IBookService

packagecom.sterning.books.services.iface;

importjava.util.List;

importcom.sterning.books.model.Books;

publicinterface IBooksService ...{
List getAll();//获得所有记录
List getBooks(int pageSize, intstartRow);//获得所有记录
int getRows();//获得总行数
int getRows(String fieldname,Stringvalue);//获得总行数
List queryBooks(String fieldname,Stringvalue);//根据条件查询
List getBooks(String fieldname,Stringvalue,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:
packagecom.sterning.books.services;
importjava.util.List;
importcom.sterning.books.dao.iface.BooksDao;
importcom.sterning.books.model.Books;
importcom.sterning.books.services.iface.IBooksService;
publicclass BooksService implements IBooksService{
privateBooksDao booksDao;
publicBooksService(){}
/**
* 函数说明:添加信息
* 参数说明:对象
* 返回值:
*/
public void addBook(Books book) {
booksDao.addBook(book);
}
/**
* 函数说明:删除信息
* 参数说明:对象
* 返回值:
*/
public void deleteBook(String bookId) {
Booksbook=booksDao.getBook(bookId);
booksDao.deleteBook(book);
}
/**
* 函数说明:获得所有的信息
* 参数说明:
* 返回值:信息的集合
*/
public List getAll() {
returnbooksDao.getAll();
}
/**
* 函数说明:获得总行数
* 参数说明:
* 返回值:总行数
*/
public int getRows() {
returnbooksDao.getRows();
}
/**
* 函数说明:获得所有的信息
* 参数说明:
* 返回值:信息的集合
*/
public List getBooks(int pageSize, intstartRow) {
returnbooksDao.getBooks(pageSize, startRow);
}
/**
* 函数说明:获得一条的信息
* 参数说明: ID
* 返回值:对象
*/
public Books getBook(String bookId) {
returnbooksDao.getBook(bookId);
}
/**
* 函数说明:获得最大ID
* 参数说明:
* 返回值:最大ID
*/
public String getMaxID() {
returnbooksDao.getMaxID();
}
/**
* 函数说明:修改信息
* 参数说明:对象
* 返回值:
*/
public void updateBook(Books book) {
booksDao.updateBook(book);
}
/**
* 函数说明:查询信息
* 参数说明:集合
* 返回值:
*/
public List queryBooks(Stringfieldname,String value) {
returnbooksDao.queryBooks(fieldname, value);
}
/**
* 函数说明:获得总行数
* 参数说明:
* 返回值:总行数
*/
public int getRows(String fieldname,Stringvalue) {
returnbooksDao.getRows(fieldname, value);
}
/**
* 函数说明:查询信息
* 参数说明:集合
* 返回值:
*/
public List getBooks(Stringfieldname,String value,int pageSize, int startRow) {
returnbooksDao.getBooks(fieldname, value,pageSize,startRow);
}
publicBooksDao getBooksDao() {
returnbooksDao;
}
publicvoid 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类

packagecom.sterning.books.web.actions;

importjava.util.Collection;
importcom.sterning.books.model.Books;
importcom.sterning.books.services.iface.IBooksService;
importcom.sterning.commons.AbstractAction;
importcom.sterning.commons.Pager;
importcom.sterning.commons.PagerService;

publicclass BooksAction extends AbstractAction {

private IBooksService booksService;
private PagerService pagerService;
privateBooks 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());
inttotalRow=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(IBooksServicebooksService) {
this.booksService = booksService;
}

public Collection getAvailableItems() {
return availableItems;
}

public String getCurrentPage() {
return currentPage;
}

public void setCurrentPage(StringcurrentPage) {
this.currentPage = currentPage;
}

public String getPagerMethod() {
return pagerMethod;
}

public void setPagerMethod(StringpagerMethod) {
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(StringqueryValue) {
this.queryValue = queryValue;
}

public String getSearchName() {
return searchName;
}

public void setSearchName(StringsearchName) {
this.searchName = searchName;
}

public String getSearchValue() {
return searchValue;
}

public void setSearchValue(StringsearchValue) {
this.searchValue = searchValue;
}

public String getQueryMap() {
return queryMap;
}

public void setQueryMap(String queryMap) {
this.queryMap = queryMap;
}

public PagerService getPagerService() {
return pagerService;
}

public void setPagerService(PagerServicepagerService) {
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),可以帮助您快捷地获得这几个对象。

HttpServletRequestrequest = ServletActionContext.getRequest();

HttpServletResponseresponse = ServletActionContext.getResponse();

HttpSessionsession = 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

<?xmlversion="1.0" encoding="UTF-8"?>
<!DOCTYPEvalidators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0//EN""http://www.opensymphony.com/xwork/xwork-validator-1.0.dtd">
<validators>
<!-- Field-Validator Syntax -->
<fieldname="book.bookName">
<field-validatortype="requiredstring">
<messagekey="book.bookName.required"/>
</field-validator>
</field>
<fieldname="book.bookAuthor">
<field-validatortype="requiredstring">
<messagekey="book.bookAuthor.required"/>
</field-validator>
</field>
<fieldname="book.bookPublish">
<field-validator type="requiredstring">
<messagekey="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:i18nname="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。

点击这里:Struts2、Spring和Hibernate应用实例(下)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: