SSH整合步骤

一.整合步骤

1. 通过MyEclipse向导,添加struts功能
2. 通过MyEclipse向导,添加Hibernate3功能:生成会话工厂的那个步骤中一定要将那个对号要去掉,不能由hibernate来生成,而是交给Spring来生成;还有就是导入jar包的时候选择复制到lib目录下这一项。

3. 通过MyEclipse向导,导入实现Spring功能,注意导入jar包的时候选择复制到lib目录下这一项。利用MyEclipse反向工程的方法,以Spring<dao>生成dao对象的方式创建Hibernate DAO,相关POJO及其xxx.hbm.xml。

4.   DAO实现类加入@Transactional标记。

5.  修改applicationContext.xml文件,增加Spring事务管理、DAO等bean的配置。

6. 编写action类。

7. 在applicationContext.xml文件中添加Action的代理bean。

8. 在struts的配置文件中,添加相应的Action,类名指向Spring中的代理bean,并加入<controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor" />和<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
  <set-property property="contextConfigLocation"
   value="/WEB-INF/classes/applicationContext.xml" />
 </plug-in>。

9. 编写Jsp文件。

10. 发布web项目。

11. 启动web服务器,运行项目

二.SSH实现关于书籍增删改查实例

1.创建mysql数据库及其表

create database book;
create table book(id int not null primary key auto_increment,bookname varchar(30),bookauthor varchar(30));

2.表现层
(1)index.jsp(首页)

[java] view plaincopyprint?
<%@ page language="java" pageEncoding="GBK" %>  
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html:html lang="true">  
<head>  
<html:base/><title>欢迎</title>  
</head>  
<body>  
<a href="book.do?method=listbook" mce_href="book.do?method=listbook">查看书籍列表</a><br>  
</body>  
</html:html>  
<%@ page language="java" pageEncoding="GBK" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html lang="true">
<head>
<html:base/><title>欢迎</title>
</head>
<body>
<a href="book.do?method=listbook" mce_href="book.do?method=listbook">查看书籍列表</a><br>
</body>
</html:html> 


(2)list.jsp(书籍列表页面)


[c-sharp] view plaincopyprint?
<%@ page contentType="text/html;charset=GBK" isELIgnored="false"%>  
<%-- 我们使用 JSTL 来访问数据 --%>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c" %>  
<%  
String path = request.getContextPath();  
String basePath =  
request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
    <head>  
        <base href="<%=basePath%>">  
        <title>书籍列表页面</title>  
        <meta http-equiv="pragma" content="no-cache">  
        <meta http-equiv="cache-control" content="no-cache">  
        <meta http-equiv="expires" content="0">  
        <mce:style><!--  
/* 给链接加入鼠标移过变色和去除下划线功能 */  
a:hover {  
    color: red;  
    text-decoration: none  
}  
--></mce:style><style mce_bogus="1">/* 给链接加入鼠标移过变色和去除下划线功能 */  
a:hover {  
    color: red;  
    text-decoration: none  
}</style>  
    </head>  
    <body>  
        <b>书籍列表页面</b>  
        <br>  
        <%-- 输出用户列表 --%>  
        <br>  
        <c:choose>  
            <c:when test="${not empty books}">  
        <table width="80%" border="1" cellpadding="0"  
            style="border-collapse: collapse;" bordercolor="#000000">  
            <tr>  
                <td>  
                    <b>书籍ID</b>  
                </td>  
                <td>  
                    <b>书籍名称</b>  
                </td>  
                <td>  
                    <b>作者</b>  
                </td>  
                <td>  
                    <b>价格</b>  
                </td>  
                <td>  
                    <b>操作</b>  
                </td>  
            </tr>  
              
            <c:forEach items="${books}" var="book">  
                <tr>  
                    <td>  
                        ${book.id}  
                    </td>  
                    <td>  
                        ${book.bookname}  
                    </td>  
                    <td>  
                        ${book.bookauthor}  
                    </td>  
                    <td>  
                        ${book.bookprice}  
                    </td>  
                    <td>  
                        <a href="<%=path%>/book.do?method=modifybook&id=${book.id}">修改</a>  
                        <a href="<%=path%>/book.do?method=deletebook&id=${book.id}">删除</a>  
                    </td>  
                </tr>  
            </c:forEach>  
              
        </table>  
        </c:when>  
        <c:otherwise>抱歉,没有找到相关的记录!</c:otherwise>  
            </c:choose>  
        <a href="<%=path%>/new.jsp">添加书籍</a>  
        <form action="<%=path%>/book.do?method=searchbook" method="post" οnsubmit="return checkSearchForm(this);">  
            <fieldset>  
                <legend>  
                    查找书籍  
                </legend>  
                书籍名:  
                <input name="bookname">  
                <input type="submit" value="查找">  
            </fieldset>  
        </form>  
    </body>  
</html>  
<%@ page contentType="text/html;charset=GBK" isELIgnored="false"%>
<%-- 我们使用 JSTL 来访问数据 --%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c" %>
<%
String path = request.getContextPath();
String basePath =
request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>书籍列表页面</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<mce:style><!--
/* 给链接加入鼠标移过变色和去除下划线功能 */
a:hover {
color: red;
text-decoration: none
}
--></mce:style><style mce_bogus="1">/* 给链接加入鼠标移过变色和去除下划线功能 */
a:hover {
color: red;
text-decoration: none
}</style>
</head>
<body>
<b>书籍列表页面</b>
<br>
<%-- 输出用户列表 --%>
<br>
<c:choose>
<c:when test="${not empty books}">
<table width="80%" border="1" cellpadding="0"
style="border-collapse: collapse;" bordercolor="#000000">
<tr>
<td>
<b>书籍ID</b>
</td>
<td>
<b>书籍名称</b>
</td>
<td>
<b>作者</b>
</td>
<td>
   <b>价格</b>
</td>
<td>
   <b>操作</b>
</td>
</tr>

<c:forEach items="${books}" var="book">
<tr>
<td>
${book.id}
</td>
<td>
${book.bookname}
</td>
<td>
   ${book.bookauthor}
</td>
<td>
   ${book.bookprice}
</td>
<td>
<a href="<%=path%>/book.do?method=modifybook&id=${book.id}">修改</a>
<a href="<%=path%>/book.do?method=deletebook&id=${book.id}">删除</a>
</td>
</tr>
</c:forEach>

</table>
</c:when>
<c:otherwise>抱歉,没有找到相关的记录!</c:otherwise>
</c:choose>
<a href="<%=path%>/new.jsp">添加书籍</a>
<form action="<%=path%>/book.do?method=searchbook" method="post" οnsubmit="return checkSearchForm(this);">
<fieldset>
<legend>
查找书籍
</legend>
书籍名:
<input name="bookname">
<input type="submit" value="查找">
</fieldset>
</form>
</body>
</html>  


(3)new.jsp(新增书籍页面)


[c-sharp] view plaincopyprint?
<%@ page language="java" pageEncoding="GBK"%>  
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>  
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
    <head>  
        <title>添加书籍</title>  
        <meta http-equiv="pragma" content="no-cache">  
        <meta http-equiv="cache-control" content="no-cache">  
        <meta http-equiv="expires" content="0">  
        <mce:script type="text/javascript" src="js/form.js" mce_src="js/form.js"></mce:script>  
    </head>  
    <body>  
        <h3>  
            添加书籍  
        </h3>  
        <form action="<%=request.getContextPath()%>/book.do?method=addbook" οnsubmit="return checkForm(this);" method="post">  
            <table width="100%" border="0">  
                <tbody>  
                    <tr>  
                        <td>  
                             书籍名:  
                        </td>  
                        <td>  
                               
                            <input name="bookname"/>  
                            <br>  
                        </td>  
                    </tr>  
                    <tr>  
                        <td>  
                             作者:  
                        </td>  
                        <td>  
                               
                            <input name="bookauthor"/>  
                        </td>  
                    </tr>  
                    <tr>  
                        <td>  
                             价格:  
                        </td>  
                        <td>  
                               
                            <input name="bookprice"/>  
                        </td>  
                    </tr>  
                    <tr>  
                        <td>  
                               
                            <input type="submit" value="添加" name="button1">  
                        </td>  
                        <td>  
                               
                            <input type="Reset" value="重填" name="button2">  
                        </td>  
                    </tr>  
                </tbody>  
            </table>  
        </form>  
        <input type="button" οnclick="document.location='<%=request.getContextPath()%>/book.do?method=listbook';"  
            value="  
返回列表">  
    </body>  
</html>  
<%@ page language="java" pageEncoding="GBK"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>添加书籍</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<mce:script type="text/javascript" src="js/form.js" mce_src="js/form.js"></mce:script>
</head>
<body>
<h3>
添加书籍
</h3>
<form action="<%=request.getContextPath()%>/book.do?method=addbook" οnsubmit="return checkForm(this);" method="post">
<table width="100%" border="0">
<tbody>
<tr>
<td>
书籍名:
</td>
<td>
 
<input name="bookname"/>
<br>
</td>
</tr>
<tr>
<td>
作者:
</td>
<td>
 
<input name="bookauthor"/>
</td>
</tr>
<tr>
<td>
价格:
</td>
<td>
 
<input name="bookprice"/>
</td>
</tr>
<tr>
<td>
 
<input type="submit" value="添加" name="button1">
</td>
<td>
 
<input type="Reset" value="重填" name="button2">
</td>
</tr>
</tbody>
</table>
</form>
<input type="button" οnclick="document.location='<%=request.getContextPath()%>/book.do?method=listbook';"
value="
返回列表">
</body>
</html>


(4)edit.jsp(书籍修改页面)


[c-sharp] view plaincopyprint?
<%@ page language="java" pageEncoding="GBK" isELIgnored="false"%>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
    <head>  
        <title>修改书籍</title>  
        <meta http-equiv="pragma" content="no-cache">  
        <meta http-equiv="cache-control" content="no-cache">  
        <meta http-equiv="expires" content="0">  
        <mce:script type="text/javascript" src="js/form.js" mce_src="js/form.js"></mce:script>  
    </head>  
    <body>  
        <h3>  
            修改书籍  
        </h3>  
        <form action="<%=request.getContextPath()%>/book.do?method=updatebook" οnsubmit="return checkForm(this);" method="post">  
            <input type="hidden" value="${book.id}" name="id"/>  
            <table width="100%" border="0">  
                <tbody>  
                    <tr>  
                        <td>  
                             书籍名:  
                        </td>  
                        <td>  
                               
                            <input name="bookname" value="${book.bookname}"/>  
                            <br>  
                        </td>  
                    </tr>  
                    <tr>  
                        <td>  
                             作者:  
                        </td>  
                        <td>  
                               
                            <input name="bookauthor" value="${book.bookauthor}"/>  
                        </td>  
                    </tr>  
                    <tr>  
                        <td>  
                             价格:  
                        </td>  
                        <td>  
                               
                            <input name="bookprice" value="${book.bookprice}"/>  
                        </td>  
                    </tr>  
                    <tr>  
                        <td>  
                               
                            <input type="submit" value="提交" >  
                        </td>  
                        <td>  
                               
                            <input type="reset" value="重填">  
                        </td>  
                    </tr>  
                </tbody>  
            </table>  
        </form>  
        <input type="button" οnclick="document.location='book.do?method=listbook';" value="返回列表">  
    </body>  
</html>  
<%@ page language="java" pageEncoding="GBK" isELIgnored="false"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>修改书籍</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<mce:script type="text/javascript" src="js/form.js" mce_src="js/form.js"></mce:script>
</head>
<body>
<h3>
修改书籍
</h3>
<form action="<%=request.getContextPath()%>/book.do?method=updatebook" οnsubmit="return checkForm(this);" method="post">
   <input type="hidden" value="${book.id}" name="id"/>
<table width="100%" border="0">
<tbody>
<tr>
<td>
书籍名:
</td>
<td>
 
<input name="bookname" value="${book.bookname}"/>
<br>
</td>
</tr>
<tr>
<td>
作者:
</td>
<td>
 
<input name="bookauthor" value="${book.bookauthor}"/>
</td>
</tr>
<tr>
<td>
价格:
</td>
<td>
 
<input name="bookprice" value="${book.bookprice}"/>
</td>
</tr>
<tr>
<td>
 
<input type="submit" value="提交" >
</td>
<td>
 
<input type="reset" value="重填">
</td>
</tr>
</tbody>
</table>
</form>
<input type="button" οnclick="document.location='book.do?method=listbook';" value="返回列表">
</body>
</html> 


(5)error.jsp(错误公用页面)


[c-sharp] view plaincopyprint?
<%@ page language="java" pageEncoding="GBK" isELIgnored="false"%>  
<%  
String path = request.getContextPath();  
String basePath =  
request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
<head>  
<base href="<%=basePath%>">  
<title>出错了!</title>  
</head>  
<body>  
出错了!<br/>  
详细信息是:<br/>  
${message}<br/><br/>  
<a href="javascript:history.back();" mce_href="javascript:history.back();">返回</a>  
</body>  
</html>  
<%@ page language="java" pageEncoding="GBK" isELIgnored="false"%>
<%
String path = request.getContextPath();
String basePath =
request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>出错了!</title>
</head>
<body>
出错了!<br/>
详细信息是:<br/>
${message}<br/><br/>
<a href="javascript:history.back();" mce_href="javascript:history.back();">返回</a>
</body>
</html> 


(6)form.js


[c-sharp] view plaincopyprint?
// 验证表单输入不为空的脚本代码   
function checkForm(form) {  
    if (form.bookname.value == "") {  
        alert("书名不能为空!");  
        form.bookname.focus();  
        return false;  
    }  
    if (form.bookauthor.value == "") {  
        alert("作者不能为空!");  
        form.bookauthor.focus();  
        return false;  
    }  
    if (form.bookprice.value == "") {  
        alert("价格不能为空!");  
        form.bookprice.focus();  
        return false;  
    }  
    return true;  
}  
function checkSearchForm(form){  
    if(form.bookname.value.match(/^/s*$/)){  
        alert("查询条件不能为空!");  
        form.bookname.focus();  
        return false;  
    }  
    return true;  
}  
// 验证表单输入不为空的脚本代码
function checkForm(form) {
if (form.bookname.value == "") {
alert("书名不能为空!");
form.bookname.focus();
return false;
}
if (form.bookauthor.value == "") {
alert("作者不能为空!");
form.bookauthor.focus();
return false;
}
if (form.bookprice.value == "") {
alert("价格不能为空!");
form.bookprice.focus();
return false;
}
return true;
}
function checkSearchForm(form){
if(form.bookname.value.match(/^/s*$/)){
alert("查询条件不能为空!");
form.bookname.focus();
return false;
}
return true;



3.公用类及其javabean


(1)EncodingFilter.java(过滤器)


[c-sharp] view plaincopyprint?
package filter;  
import java.io.IOException;  
import javax.servlet.Filter;  
import javax.servlet.FilterChain;  
import javax.servlet.FilterConfig;  
import javax.servlet.ServletException;  
import javax.servlet.ServletRequest;  
import javax.servlet.ServletResponse;  
public class EncodingFilter implements Filter {  
    protected FilterConfig config;  
    protected String Encoding = null;  
    public void init(FilterConfig config) throws ServletException {  
        this.config = config;  
        this.Encoding = config.getInitParameter("Encoding");  
    }  
    public void doFilter(ServletRequest request, ServletResponse response,  
            FilterChain chain) throws IOException, ServletException {  
        if (request.getCharacterEncoding() == null) {  
            if (Encoding != null) {  
                request.setCharacterEncoding(Encoding);  
                response.setCharacterEncoding(Encoding);  
            }  
        }  
        chain.doFilter(request, response);  
    }  
    public void destroy() {  
    }  
}  
package filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class EncodingFilter implements Filter {
protected FilterConfig config;
protected String Encoding = null;
public void init(FilterConfig config) throws ServletException {
this.config = config;
this.Encoding = config.getInitParameter("Encoding");
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (request.getCharacterEncoding() == null) {
if (Encoding != null) {
request.setCharacterEncoding(Encoding);
response.setCharacterEncoding(Encoding);
}
}
chain.doFilter(request, response);
}
public void destroy() {
}
}




(2)book.java


[c-sharp] view plaincopyprint?
package dao;  
/** 
 * Book entity. @author MyEclipse Persistence Tools 
 */  
public class Book implements java.io.Serializable {  
    // Fields   
    private Integer id;  
    private String bookname;  
    private String bookauthor;  
    private Float bookprice;  
    // Constructors   
    /** default constructor */  
    public Book() {  
    }  
    /** full constructor */  
    public Book(String bookname, String bookauthor, Float bookprice) {  
        this.bookname = bookname;  
        this.bookauthor = bookauthor;  
        this.bookprice = bookprice;  
    }  
    // Property accessors   
    public Integer getId() {  
        return this.id;  
    }  
    public void setId(Integer id) {  
        this.id = id;  
    }  
    public String getBookname() {  
        return this.bookname;  
    }  
    public void setBookname(String bookname) {  
        this.bookname = bookname;  
    }  
    public String getBookauthor() {  
        return this.bookauthor;  
    }  
    public void setBookauthor(String bookauthor) {  
        this.bookauthor = bookauthor;  
    }  
    public Float getBookprice() {  
        return this.bookprice;  
    }  
    public void setBookprice(Float bookprice) {  
        this.bookprice = bookprice;  
    }  
}  
package dao;
/**
 * Book entity. @author MyEclipse Persistence Tools
 */
public class Book implements java.io.Serializable {
// Fields
private Integer id;
private String bookname;
private String bookauthor;
private Float bookprice;
// Constructors
/** default constructor */
public Book() {
}
/** full constructor */
public Book(String bookname, String bookauthor, Float bookprice) {
this.bookname = bookname;
this.bookauthor = bookauthor;
this.bookprice = bookprice;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBookname() {
return this.bookname;
}
public void setBookname(String bookname) {
this.bookname = bookname;
}
public String getBookauthor() {
return this.bookauthor;
}
public void setBookauthor(String bookauthor) {
this.bookauthor = bookauthor;
}
public Float getBookprice() {
return this.bookprice;
}
public void setBookprice(Float bookprice) {
this.bookprice = bookprice;
}



4.DAO层


BookDAO.java


[c-sharp] view plaincopyprint?
package dao;  
import java.util.List;  
import org.hibernate.LockMode;  
import org.hibernate.Query;  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
import org.springframework.context.ApplicationContext;  
import org.springframework.context.support.ClassPathXmlApplicationContext;  
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;  
import org.springframework.transaction.annotation.Transactional;  
/** 
 * A data access object (DAO) providing persistence and search support for Book 
 * entities. Transaction control of the save(), update() and delete() operations 
 * can directly support Spring container-managed transactions or they can be 
 * augmented to handle user-managed Spring transactions. Each of these methods 
 * provides additional information for how to configure it for the desired type 
 * of transaction control. 
 *  
 * @see dao.Book 
 * @author MyEclipse Persistence Tools 
 */  
@Transactional  
public class BookDAO extends HibernateDaoSupport {  
    private static final Logger log = LoggerFactory.getLogger(BookDAO.class);  
    // property constants   
    public static final String BOOKNAME = "bookname";  
    public static final String BOOKAUTHOR = "bookauthor";  
    public static final String BOOKPRICE = "bookprice";  
    protected void initDao() {  
        // do nothing   
    }  
    public void save(Book transientInstance) {  
        log.debug("saving Book instance");  
        try {  
            getHibernateTemplate().save(transientInstance);  
            log.debug("save successful");  
        } catch (RuntimeException re) {  
            log.error("save failed", re);  
            throw re;  
        }  
    }  
    public void update(Book transientInstance) {  
        log.debug("saving Book instance");  
        try {  
            getHibernateTemplate().update(transientInstance);  
            log.debug("save successful");  
        } catch (RuntimeException re) {  
            log.error("save failed", re);  
            throw re;  
        }  
    }  
    public void delete(Book persistentInstance) {  
        log.debug("deleting Book instance");  
        try {  
            getHibernateTemplate().delete(persistentInstance);  
            log.debug("delete successful");  
        } catch (RuntimeException re) {  
            log.error("delete failed", re);  
            throw re;  
        }  
    }  
    public Book findById(java.lang.Integer id) {  
        log.debug("getting Book instance with id: " + id);  
        try {  
            Book instance = (Book) getHibernateTemplate().get("dao.Book", id);  
            return instance;  
        } catch (RuntimeException re) {  
            log.error("get failed", re);  
            throw re;  
        }  
    }  
    public List findByExample(Book instance) {  
        log.debug("finding Book instance by example");  
        try {  
            List results = getHibernateTemplate().findByExample(instance);  
            log.debug("find by example successful, result size: "  
                    + results.size());  
            return results;  
        } catch (RuntimeException re) {  
            log.error("find by example failed", re);  
            throw re;  
        }  
    }  
    public List findByProperty(String propertyName, Object value) {  
        log.debug("finding Book instance with property: " + propertyName  
                + ", value: " + value);  
        try {  
            String queryString = "from Book as model where model."  
                    + propertyName + "like = ";  
            return getHibernateTemplate().find(queryString, value);  
        } catch (RuntimeException re) {  
            log.error("find by property name failed", re);  
            throw re;  
        }  
    }  
    public List findByBookname(String  bookname) {  
        String sql="from Book where bookname like '%"+bookname+"%'";  
        Query query=this.getSession().createQuery(sql);  
        return query.list();  
    }  
    public List findByBookauthor(Object bookauthor) {  
        return findByProperty(BOOKAUTHOR, bookauthor);  
    }  
    public List findByBookprice(Object bookprice) {  
        return findByProperty(BOOKPRICE, bookprice);  
    }  
    public List findAll() {  
        log.debug("finding all Book instances");  
        try {  
            String queryString = "from Book";  
            return getHibernateTemplate().find(queryString);  
        } catch (RuntimeException re) {  
            log.error("find all failed", re);  
            throw re;  
        }  
    }  
    public Book merge(Book detachedInstance) {  
        log.debug("merging Book instance");  
        try {  
            Book result = (Book) getHibernateTemplate().merge(detachedInstance);  
            log.debug("merge successful");  
            return result;  
        } catch (RuntimeException re) {  
            log.error("merge failed", re);  
            throw re;  
        }  
    }  
    public void attachDirty(Book instance) {  
        log.debug("attaching dirty Book instance");  
        try {  
            getHibernateTemplate().saveOrUpdate(instance);  
            log.debug("attach successful");  
        } catch (RuntimeException re) {  
            log.error("attach failed", re);  
            throw re;  
        }  
    }  
    public void attachClean(Book instance) {  
        log.debug("attaching clean Book instance");  
        try {  
            getHibernateTemplate().lock(instance, LockMode.NONE);  
            log.debug("attach successful");  
        } catch (RuntimeException re) {  
            log.error("attach failed", re);  
            throw re;  
        }  
    }  
    public static BookDAO getFromApplicationContext(ApplicationContext ctx) {  
        return (BookDAO) ctx.getBean("BookDAO");  
    }  
    public static void main(String[] args) {  
        ApplicationContext ctx =  
        new  
        ClassPathXmlApplicationContext("applicationContext.xml");  
        BookDAO dao = (BookDAO)ctx.getBean("BookDAO");  
        Book book = new Book();  
        book.setBookname("数学");  
        book.setBookauthor("张三");  
        book.setBookprice(12.0f);  
        dao.save(book);  
        }  
}  
package dao;
import java.util.List;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;
/**
 * A data access object (DAO) providing persistence and search support for Book
 * entities. Transaction control of the save(), update() and delete() operations
 * can directly support Spring container-managed transactions or they can be
 * augmented to handle user-managed Spring transactions. Each of these methods
 * provides additional information for how to configure it for the desired type
 * of transaction control.
 * 
 * @see dao.Book
 * @author MyEclipse Persistence Tools
 */
@Transactional
public class BookDAO extends HibernateDaoSupport {
private static final Logger log = LoggerFactory.getLogger(BookDAO.class);
// property constants
public static final String BOOKNAME = "bookname";
public static final String BOOKAUTHOR = "bookauthor";
public static final String BOOKPRICE = "bookprice";
protected void initDao() {
// do nothing
}
public void save(Book transientInstance) {
log.debug("saving Book instance");
try {
getHibernateTemplate().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void update(Book transientInstance) {
log.debug("saving Book instance");
try {
getHibernateTemplate().update(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void delete(Book persistentInstance) {
log.debug("deleting Book instance");
try {
getHibernateTemplate().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public Book findById(java.lang.Integer id) {
log.debug("getting Book instance with id: " + id);
try {
Book instance = (Book) getHibernateTemplate().get("dao.Book", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List findByExample(Book instance) {
log.debug("finding Book instance by example");
try {
List results = getHibernateTemplate().findByExample(instance);
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
public List findByProperty(String propertyName, Object value) {
log.debug("finding Book instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from Book as model where model."
+ propertyName + "like = ";
return getHibernateTemplate().find(queryString, value);
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}
public List findByBookname(String  bookname) {
String sql="from Book where bookname like '%"+bookname+"%'";
Query query=this.getSession().createQuery(sql);
return query.list();
}
public List findByBookauthor(Object bookauthor) {
return findByProperty(BOOKAUTHOR, bookauthor);
}
public List findByBookprice(Object bookprice) {
return findByProperty(BOOKPRICE, bookprice);
}
public List findAll() {
log.debug("finding all Book instances");
try {
String queryString = "from Book";
return getHibernateTemplate().find(queryString);
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
public Book merge(Book detachedInstance) {
log.debug("merging Book instance");
try {
Book result = (Book) getHibernateTemplate().merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public void attachDirty(Book instance) {
log.debug("attaching dirty Book instance");
try {
getHibernateTemplate().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(Book instance) {
log.debug("attaching clean Book instance");
try {
getHibernateTemplate().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public static BookDAO getFromApplicationContext(ApplicationContext ctx) {
return (BookDAO) ctx.getBean("BookDAO");
}
public static void main(String[] args) {
ApplicationContext ctx =
new
ClassPathXmlApplicationContext("applicationContext.xml");
BookDAO dao = (BookDAO)ctx.getBean("BookDAO");
Book book = new Book();
book.setBookname("数学");
book.setBookauthor("张三");
book.setBookprice(12.0f);
dao.save(book);
}



5.service层


(1)IBookManager.java(接口)


[c-sharp] view plaincopyprint?
package service;  
import java.util.List;  
import dao.Book;  
public interface IBookManager {  
    /** 
     * 根据ID查找用户信息。 
     *  
     * @param id 
     *            用户编号 
     * @return 找到的用户对象,找不到时返回null 
     */  
    public Book findById(int id);  
    /** 
     * 更新用户对象。 
     *  
     * @param Book 
     *            被更新的用户 
     * @return 更新成功与否 
     */  
    public boolean update(Book Book);  
    public boolean save(Book Book);  
    /** 
     * 删除用户对象。 
     *  
     * @param Book 
     *            被删除的用户 
     * @return 删除成功与否 
     */  
    public boolean delete(Book Book);  
    /** 
     * 根据用户名查找用户。 
     *  
     * @param username 
     *            用户名 
     * @return 包含此用户名的用户列表 
     */  
    public List<Book> findByBookname(String username);  
    public List findAll();  
}  
package service;
import java.util.List;
import dao.Book;
public interface IBookManager {
/**
* 根据ID查找用户信息。

* @param id
*            用户编号
* @return 找到的用户对象,找不到时返回null
*/
public Book findById(int id);
/**
* 更新用户对象。

* @param Book
*            被更新的用户
* @return 更新成功与否
*/
public boolean update(Book Book);
    public boolean save(Book Book);
/**
* 删除用户对象。

* @param Book
*            被删除的用户
* @return 删除成功与否
*/
public boolean delete(Book Book);
/**
* 根据用户名查找用户。

* @param username
*            用户名
* @return 包含此用户名的用户列表
*/
public List<Book> findByBookname(String username);
public List findAll();
}
 


(2)BookManager.java(实现类)


[c-sharp] view plaincopyprint?
package service;  
import java.util.List;  
import org.springframework.context.ApplicationContext;  
import org.springframework.context.support.ClassPathXmlApplicationContext;  
import dao.Book;  
import dao.BookDAO;  
public class BookManager implements IBookManager {  
    private BookDAO bookdao;  
      
    public boolean delete(Book book) {  
        try {  
            bookdao.delete(book);  
            return true;  
        } catch (Exception e) {  
        }  
        return false;  
    }  
    public Book findById(int id) {  
        return bookdao.findById(id);  
    }  
    public List findAll(){  
        return bookdao.findAll();  
    }  
    public List<Book> findByBookname(String bookname) {  
        return bookdao.findByBookname(bookname);  
    }  
    public boolean update(Book Book) {  
        try {  
            bookdao.update(Book);  
            return true;  
        } catch (Exception e) {  
        }  
        return false;  
    }  
    public boolean save(Book Book){  
        try {  
            bookdao.save(Book);  
            return true;  
        } catch (Exception e) {  
        }  
        return false;  
    }  
    public dao.BookDAO getBookdao() {  
        return bookdao;  
    }  
    public void setBookdao(dao.BookDAO bookdao) {  
        this.bookdao = bookdao;  
    }  
}  
package service;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import dao.Book;
import dao.BookDAO;
public class BookManager implements IBookManager {
private BookDAO bookdao;

public boolean delete(Book book) {
try {
bookdao.delete(book);
return true;
} catch (Exception e) {
}
return false;
}
public Book findById(int id) {
return bookdao.findById(id);
}
public List findAll(){
return bookdao.findAll();
}
public List<Book> findByBookname(String bookname) {
return bookdao.findByBookname(bookname);
}
public boolean update(Book Book) {
try {
bookdao.update(Book);
return true;
} catch (Exception e) {
}
return false;
}
    public boolean save(Book Book){
    try {
    bookdao.save(Book);
return true;
} catch (Exception e) {
}
return false;
    }
public dao.BookDAO getBookdao() {
return bookdao;
}
public void setBookdao(dao.BookDAO bookdao) {
this.bookdao = bookdao;
}
}
 


6.Action处理


(1)BookForm.java


[c-sharp] view plaincopyprint?
package com.zxc.struts.form;  
import org.apache.struts.action.ActionForm;  
public class BookForm extends ActionForm{  
    private int id;  
    private String bookname;  
    private String bookauthor;  
    private float bookprice;  
    public int getId() {  
        return id;  
    }  
    public void setId(int id) {  
        this.id = id;  
    }  
    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 float getBookprice() {  
        return bookprice;  
    }  
    public void setBookprice(float bookprice) {  
        this.bookprice = bookprice;  
    }  
}  
package com.zxc.struts.form;
import org.apache.struts.action.ActionForm;
public class BookForm extends ActionForm{
    private int id;
    private String bookname;
    private String bookauthor;
    private float bookprice;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 float getBookprice() {
return bookprice;
}
public void setBookprice(float bookprice) {
this.bookprice = bookprice;
}
}
 


(2)BookAction.java


[java] view plaincopyprint?
/* 
 * Generated by MyEclipse Struts 
 * Template path: templates/java/JavaClass.vtl 
 */  
package com.zxc.struts.action;  
import java.util.List;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import org.apache.struts.action.ActionForm;  
import org.apache.struts.action.ActionForward;  
import org.apache.struts.action.ActionMapping;  
import org.apache.struts.actions.DispatchAction;  
import service.IBookManager;  
import com.zxc.struts.form.BookForm;  
import dao.Book;  
/**  
 * MyEclipse Struts 
 * Creation date: 10-01-2010 
 *  
 * XDoclet definition: 
 * @struts.action validate="true" 
 */  
public class BookAction extends DispatchAction {  
    private IBookManager bookManager;  
    public ActionForward addbook(ActionMapping mapping, ActionForm form,  
            HttpServletRequest request, HttpServletResponse response) {  
        // TODO Auto-generated method stub   
        BookForm bookForm=(BookForm)form;  
        Book book=new Book();  
        book.setBookname(bookForm.getBookname());  
        book.setBookauthor(bookForm.getBookauthor());  
        book.setBookprice(bookForm.getBookprice());  
        bookManager.save(book);  
        return listbook(mapping,form,request,response);  
    }  
    public ActionForward updatebook(ActionMapping mapping, ActionForm form,  
            HttpServletRequest request, HttpServletResponse response) {  
        // TODO Auto-generated method stub   
        BookForm bookForm=(BookForm)form;  
        String id=request.getParameter("id");  
        Book book=bookManager.findById(Integer.parseInt(id));  
        book.setBookname(bookForm.getBookname());  
        book.setBookauthor(bookForm.getBookauthor());  
        book.setBookprice(bookForm.getBookprice());  
        if(bookManager.update(book)){  
            return listbook(mapping,form,request,response);  
        }else{  
            String message="更新失败!";  
            request.setAttribute("message", message);  
            return mapping.findForward("message");  
        }  
    }  
    public ActionForward modifybook(ActionMapping mapping, ActionForm form,  
            HttpServletRequest request, HttpServletResponse response) {  
        // TODO Auto-generated method stub   
        String id=request.getParameter("id");  
        Book book=bookManager.findById(Integer.parseInt(id));  
        request.setAttribute("book", book);  
        return mapping.findForward("edit");  
    }  
    public ActionForward deletebook(ActionMapping mapping, ActionForm form,  
            HttpServletRequest request, HttpServletResponse response) {  
        // TODO Auto-generated method stub   
        String id=request.getParameter("id");  
        Book book=bookManager.findById(Integer.parseInt(id));  
        if(bookManager.delete(book)){  
            return listbook(mapping,form,request,response);  
        }else{  
            String message="删除失败!";  
            request.setAttribute("message", message);  
            return mapping.findForward("message");  
        }  
    }  
    public ActionForward listbook(ActionMapping mapping, ActionForm form,  
            HttpServletRequest request, HttpServletResponse response) {  
        // TODO Auto-generated method stub   
        List books=bookManager.findAll();  
        request.setAttribute("books", books);  
        return mapping.findForward("list");  
    }  
    public ActionForward searchbook(ActionMapping mapping, ActionForm form,  
            HttpServletRequest request, HttpServletResponse response) {  
        // TODO Auto-generated method stub   
        String bookname=request.getParameter("bookname");  
        List books=bookManager.findByBookname(bookname);  
        request.setAttribute("books", books);  
        return mapping.findForward("list");  
    }   
    public void setBookManager(IBookManager bookManager) {  
        this.bookManager = bookManager;  
    }  
    public IBookManager getBookManager() {  
        return bookManager;  
    }  
}  
/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package com.zxc.struts.action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import service.IBookManager;
import com.zxc.struts.form.BookForm;
import dao.Book;
/** 
 * MyEclipse Struts
 * Creation date: 10-01-2010
 * 
 * XDoclet definition:
 * @struts.action validate="true"
 */
public class BookAction extends DispatchAction {
private IBookManager bookManager;
public ActionForward addbook(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
BookForm bookForm=(BookForm)form;
Book book=new Book();
book.setBookname(bookForm.getBookname());
book.setBookauthor(bookForm.getBookauthor());
book.setBookprice(bookForm.getBookprice());
bookManager.save(book);
return listbook(mapping,form,request,response);
}
public ActionForward updatebook(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
BookForm bookForm=(BookForm)form;
String id=request.getParameter("id");
Book book=bookManager.findById(Integer.parseInt(id));
book.setBookname(bookForm.getBookname());
book.setBookauthor(bookForm.getBookauthor());
book.setBookprice(bookForm.getBookprice());
if(bookManager.update(book)){
return listbook(mapping,form,request,response);
}else{
String message="更新失败!";
request.setAttribute("message", message);
return mapping.findForward("message");
}
}
public ActionForward modifybook(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
String id=request.getParameter("id");
Book book=bookManager.findById(Integer.parseInt(id));
request.setAttribute("book", book);
return mapping.findForward("edit");
}
public ActionForward deletebook(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
String id=request.getParameter("id");
Book book=bookManager.findById(Integer.parseInt(id));
if(bookManager.delete(book)){
return listbook(mapping,form,request,response);
}else{
String message="删除失败!";
request.setAttribute("message", message);
return mapping.findForward("message");
}
}
public ActionForward listbook(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
List books=bookManager.findAll();
request.setAttribute("books", books);
return mapping.findForward("list");
}
public ActionForward searchbook(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
String bookname=request.getParameter("bookname");
List books=bookManager.findByBookname(bookname);
request.setAttribute("books", books);
return mapping.findForward("list");

public void setBookManager(IBookManager bookManager) {
this.bookManager = bookManager;
}
public IBookManager getBookManager() {
return bookManager;
}



7.配置文件


(1)log4j.properties


[c-sharp] view plaincopyprint?
log4j.rootLogger=WARN, stdout  
log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n  
log4j.rootLogger=WARN, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n 


(2)hibernate.cfg.xml


[c-sharp] view plaincopyprint?
<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC  
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
<!-- Generated by MyEclipse Hibernate Tools.                   -->  
<hibernate-configuration>  
    <session-factory>  
        <property name="dialect">  
            org.hibernate.dialect.MySQLDialect  
        </property>  
        <property name="connection.url">  
            jdbc:mysql://localhost:3306/book   
        </property>  
        <property name="connection.username">root</property>  
        <property name="connection.password">123</property>  
        <property name="connection.driver_class">  
            com.mysql.jdbc.Driver  
        </property>  
        <property name="myeclipse.connection.profile">mysql5</property>  
        <mapping resource="dao/Book.hbm.xml" />  
    </session-factory>  
</hibernate-configuration>  
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>
<session-factory>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/book
</property>
<property name="connection.username">root</property>
<property name="connection.password">123</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="myeclipse.connection.profile">mysql5</property>
<mapping resource="dao/Book.hbm.xml" />
</session-factory>
</hibernate-configuration> 


(3)book.hbm.xml


[c-sharp] view plaincopyprint?
<?xml version="1.0" encoding="utf-8"?>  
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
<!--   
    Mapping file autogenerated by MyEclipse Persistence Tools  
-->  
<hibernate-mapping>  
    <class name="dao.Book" table="book" catalog="book">  
        <id name="id" type="java.lang.Integer">  
            <column name="id" />  
            <generator class="increment" />  
        </id>  
        <property name="bookname" type="java.lang.String">  
            <column name="bookname" length="30" />  
        </property>  
        <property name="bookauthor" type="java.lang.String">  
            <column name="bookauthor" length="30" />  
        </property>  
        <property name="bookprice" type="java.lang.Float">  
            <column name="bookprice" precision="12" scale="0" />  
        </property>  
    </class>  
</hibernate-mapping>  
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="dao.Book" table="book" catalog="book">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="increment" />
        </id>
        <property name="bookname" type="java.lang.String">
            <column name="bookname" length="30" />
        </property>
        <property name="bookauthor" type="java.lang.String">
            <column name="bookauthor" length="30" />
        </property>
        <property name="bookprice" type="java.lang.Float">
            <column name="bookprice" precision="12" scale="0" />
        </property>
    </class>
</hibernate-mapping>
 


(4)struts-config.xml


[c-sharp] view plaincopyprint?
<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">  
<struts-config>  
    <form-beans>  
    <form-bean name="bookForm" type="com.zxc.struts.form.BookForm"/>  
    </form-beans>  
    <global-exceptions />  
    <global-forwards />  
    <action-mappings >  
    <action  
      path="/book"  
      name="bookForm"  
      parameter="method"  
      type="com.zxc.struts.action.BookAction"  
      cancellable="true" >  
      <forward name="list" path="/list.jsp"/>  
      <forward name="edit" path="/edit.jsp"/>  
      <forward name="message" path="/error.jsp"/>  
    </action>  
    </action-mappings>  
    <controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor" />  
    <message-resources parameter="com.zxc.struts.ApplicationResources" />  
    <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">  
        <set-property property="contextConfigLocation"  
            value="/WEB-INF/classes/applicationContext.xml" />  
    </plug-in>  
</struts-config>  
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="bookForm" type="com.zxc.struts.form.BookForm"/>
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings >
    <action
      path="/book"
      name="bookForm"
      parameter="method"
      type="com.zxc.struts.action.BookAction"
      cancellable="true" >
      <forward name="list" path="/list.jsp"/>
      <forward name="edit" path="/edit.jsp"/>
      <forward name="message" path="/error.jsp"/>
    </action>
</action-mappings>
<controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor" />
<message-resources parameter="com.zxc.struts.ApplicationResources" />
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="/WEB-INF/classes/applicationContext.xml" />
</plug-in>
</struts-config>
 


(5)applicationContext.xml


[java] view plaincopyprint?
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
    xmlns:tx="http://www.springframework.org/schema/tx"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
    http://www.springframework.org/schema/tx   
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   
    ">  
    <tx:annotation-driven transaction-manager="transactionManager"  
        proxy-target-class="true" />  
    <bean id="sessionFactory"  
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
        <property name="configLocation" value="classpath:hibernate.cfg.xml">  
        </property>  
    </bean>  
    <bean id="BookDAO" class="dao.BookDAO">  
        <property name="sessionFactory">  
            <ref bean="sessionFactory" />  
        </property>  
    </bean>  
    <!-- 声明一个 Hibernate 3 的事务管理器供代理类自动管理事务用 -->  
    <bean id="transactionManager"  
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
        <property name="sessionFactory">  
            <ref local="sessionFactory" />  
        </property>  
    </bean>  
<!-- book业务处理类-->  
    <bean id="bookManager" class="service.BookManager">  
        <property name="bookdao">  
            <ref local="BookDAO"/>  
        </property>  
    </bean>  
    <bean name="/book" class="com.zxc.struts.action.BookAction">  
    <property name="bookManager">  
        <ref local="bookManager"/>  
    </property>  
    </bean>  
</beans>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
">
<tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="true" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml">
</property>
</bean>
<bean id="BookDAO" class="dao.BookDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<!-- 声明一个 Hibernate 3 的事务管理器供代理类自动管理事务用 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<!-- book业务处理类-->
<bean id="bookManager" class="service.BookManager">
   <property name="bookdao">
       <ref local="BookDAO"/>
   </property>
</bean>
<bean name="/book" class="com.zxc.struts.action.BookAction">
<property name="bookManager">
   <ref local="bookManager"/>
</property>
</bean>
</beans> 


(6)web.xml


[c-sharp] view plaincopyprint?
<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  <servlet>  
    <servlet-name>action</servlet-name>  
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>  
    <init-param>  
      <param-name>config</param-name>  
      <param-value>/WEB-INF/struts-config.xml</param-value>  
    </init-param>  
    <init-param>  
      <param-name>debug</param-name>  
      <param-value>3</param-value>  
    </init-param>  
    <init-param>  
      <param-name>detail</param-name>  
      <param-value>3</param-value>  
    </init-param>  
    <load-on-startup>0</load-on-startup>  
  </servlet>  
  <servlet-mapping>  
    <servlet-name>action</servlet-name>  
    <url-pattern>*.do</url-pattern>  
  </servlet-mapping>  
  <!--过滤器 -->  
    <filter>  
        <filter-name>Filter</filter-name>  
        <filter-class>  
            filter.EncodingFilter<!-- 过滤器类 -->  
        </filter-class>  
        <init-param>  
            <param-name>Encoding</param-name>  
            <param-value>gbk</param-value>  
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>Filter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
  <welcome-file-list>  
    <welcome-file>index.jsp</welcome-file>  
  </welcome-file-list>  
</web-app>  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值