SSH實現的增刪改查實例

SSH實現的增刪改查實例

 .整合步驟

1. 通過MyEclipse嚮導,添加struts功能

2. 通過MyEclipse嚮導,添加Hibernate3功能:生成會話工廠的那個步驟中一定要將那個對號要去掉,不能由hibernate來生成,而是交給Spring來生成;還有就是導入jar包的時候選擇複製到lib目錄下這一項。

3. 通過MyEclipse嚮導,導入實現Spring功能,注意導入jar包的時候選擇複製到lib目錄下這一項。

3. 利用MyEclipse反向工程的方法,以Spring<dao>生成dao對象的方式創建Hibernate DAO,相關POJO及其xxx.hbm.xml

4.   DAO實現類加入@Transactional標記。

5.  修改applicationContext.xml文件,增加Spring事務管理、DAObean的配置。

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(首頁)

1.  <%@ page language="java" pageEncoding="GBK" %>  

2.  <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>  

3.  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  

4.  <html:html lang="true">  

5.  <head>  

6.  <html:base/><title>歡迎</title>  

7.  </head>  

8.  <body>  

9.  <a href="book.do?method=listbook" mce_href="book.do?method=listbook">查看書籍列表</a><br>  

10. </body>  

11. </html:html>  

 

(2)list.jsp(書籍列表頁面)

1.  <%@ page contentType="text/html;charset=GBK" isELIgnored="false"%>  

2.  <%-- 我們使用 JSTL 來訪問數據 --%>  

3.  <%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c" %>  

4.  <%  

5.  String path = request.getContextPath();  

6.  String basePath =  

7.  request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  

8.  %>  

9.  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  

10. <html>  

11.     <head>  

12.         <base href="<%=basePath%>">  

13.         <title>書籍列表頁面</title>  

14.         <meta http-equiv="pragma" content="no-cache">  

15.         <meta http-equiv="cache-control" content="no-cache">  

16.         <meta http-equiv="expires" content="0">  

17.         <mce:style><!--  

18. /* 給鏈接加入鼠標移過變色和去除下劃線功能 */  

19. a:hover {  

20.     color: red;  

21.     text-decoration: none  

22. }  

23. --></mce:style><style mce_bogus="1">/* 給鏈接加入鼠標移過變色和去除下劃線功能 */  

24. a:hover {  

25.     color: red;  

26.     text-decoration: none  

27. }</style>  

28.     </head>  

29.     <body>  

30.         <b>書籍列表頁面</b>  

31.         <br>  

32.         <%-- 輸出用戶列表 --%>  

33.         <br>  

34.         <c:choose>  

35.             <c:when test="${not empty books}">  

36.         <table width="80%" border="1" cellpadding="0"  

37.             style="border-collapse: collapse;" bordercolor="#000000">  

38.             <tr>  

39.                 <td>  

40.                     <b>書籍ID</b>  

41.                 </td>  

42.                 <td>  

43.                     <b>書籍名稱</b>  

44.                 </td>  

45.                 <td>  

46.                     <b>作者</b>  

47.                 </td>  

48.                 <td>  

49.                     <b>價格</b>  

50.                 </td>  

51.                 <td>  

52.                     <b>操作</b>  

53.                 </td>  

54.             </tr>  

55.               

56.             <c:forEach items="${books}" var="book">  

57.                 <tr>  

58.                     <td>  

59.                         ${book.id}  

60.                     </td>  

61.                     <td>  

62.                         ${book.bookname}  

63.                     </td>  

64.                     <td>  

65.                         ${book.bookauthor}  

66.                     </td>  

67.                     <td>  

68.                         ${book.bookprice}  

69.                     </td>  

70.                     <td>  

71.                         <a href="<%=path%>/book.do?method=modifybook&id=${book.id}">修改</a>  

72.                         <a href="<%=path%>/book.do?method=deletebook&id=${book.id}">刪除</a>  

73.                     </td>  

74.                 </tr>  

75.             </c:forEach>  

76.               

77.         </table>  

78.         </c:when>  

79.         <c:otherwise>抱歉,沒有找到相關的記錄!</c:otherwise>  

80.             </c:choose>  

81.         <a href="<%=path%>/new.jsp">添加書籍</a>  

82.         <form action="<%=path%>/book.do?method=searchbook" method="post" οnsubmit="return checkSearchForm(this);">  

83.             <fieldset>  

84.                 <legend>  

85.                     查找書籍  

86.                 </legend>  

87.                 書籍名:  

88.                 <input name="bookname">  

89.                 <input type="submit" value="查找">  

90.             </fieldset>  

91.         </form>  

92.     </body>  

93. </html>  

 

(3)new.jsp(新增書籍頁面)

1.  <%@ page language="java" pageEncoding="GBK"%>  

2.  <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>  

3.  <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>  

4.  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  

5.  <html>  

6.      <head>  

7.          <title>添加書籍</title>  

8.          <meta http-equiv="pragma" content="no-cache">  

9.          <meta http-equiv="cache-control" content="no-cache">  

10.         <meta http-equiv="expires" content="0">  

11.         <mce:script type="text/javascript" src="js/form.js" mce_src="js/form.js"></mce:script>  

12.     </head>  

13.     <body>  

14.         <h3>  

15.             添加書籍  

16.         </h3>  

17.         <form action="<%=request.getContextPath()%>/book.do?method=addbook" οnsubmit="return checkForm(this);" method="post">  

18.             <table width="100%" border="0">  

19.                 <tbody>  

20.                     <tr>  

21.                         <td>  

22.                              書籍名:  

23.                         </td>  

24.                         <td>  

25.                                

26.                             <input name="bookname"/>  

27.                             <br>  

28.                         </td>  

29.                     </tr>  

30.                     <tr>  

31.                         <td>  

32.                              作者:  

33.                         </td>  

34.                         <td>  

35.                                

36.                             <input name="bookauthor"/>  

37.                         </td>  

38.                     </tr>  

39.                     <tr>  

40.                         <td>  

41.                              價格:  

42.                         </td>  

43.                         <td>  

44.                                

45.                             <input name="bookprice"/>  

46.                         </td>  

47.                     </tr>  

48.                     <tr>  

49.                         <td>  

50.                                

51.                             <input type="submit" value="添加" name="button1">  

52.                         </td>  

53.                         <td>  

54.                                

55.                             <input type="Reset" value="重填" name="button2">  

56.                         </td>  

57.                     </tr>  

58.                 </tbody>  

59.             </table>  

60.         </form>  

61.         <input type="button" οnclick="document.location='<%=request.getContextPath()%>/book.do?method=listbook';"  

62.             value="  

63. 返回列表">  

64.     </body>  

65. </html>  

 

(4)edit.jsp(書籍修改頁面)

1.  <%@ page language="java" pageEncoding="GBK" isELIgnored="false"%>  

2.  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  

3.  <html>  

4.      <head>  

5.          <title>修改書籍</title>  

6.          <meta http-equiv="pragma" content="no-cache">  

7.          <meta http-equiv="cache-control" content="no-cache">  

8.          <meta http-equiv="expires" content="0">  

9.          <mce:script type="text/javascript" src="js/form.js" mce_src="js/form.js"></mce:script>  

10.     </head>  

11.     <body>  

12.         <h3>  

13.             修改書籍  

14.         </h3>  

15.         <form action="<%=request.getContextPath()%>/book.do?method=updatebook" οnsubmit="return checkForm(this);" method="post">  

16.             <input type="hidden" value="${book.id}" name="id"/>  

17.             <table width="100%" border="0">  

18.                 <tbody>  

19.                     <tr>  

20.                         <td>  

21.                              書籍名:  

22.                         </td>  

23.                         <td>  

24.                                

25.                             <input name="bookname" value="${book.bookname}"/>  

26.                             <br>  

27.                         </td>  

28.                     </tr>  

29.                     <tr>  

30.                         <td>  

31.                              作者:  

32.                         </td>  

33.                         <td>  

34.                                

35.                             <input name="bookauthor" value="${book.bookauthor}"/>  

36.                         </td>  

37.                     </tr>  

38.                     <tr>  

39.                         <td>  

40.                              價格:  

41.                         </td>  

42.                         <td>  

43.                                

44.                             <input name="bookprice" value="${book.bookprice}"/>  

45.                         </td>  

46.                     </tr>  

47.                     <tr>  

48.                         <td>  

49.                                

50.                             <input type="submit" value="提交" >  

51.                         </td>  

52.                         <td>  

53.                                

54.                             <input type="reset" value="重填">  

55.                         </td>  

56.                     </tr>  

57.                 </tbody>  

58.             </table>  

59.         </form>  

60.         <input type="button" οnclick="document.location='book.do?method=listbook';" value="返回列表">  

61.     </body>  

62. </html>  

(5)error.jsp(錯誤公用頁面)

1.  <%@ page language="java" pageEncoding="GBK" isELIgnored="false"%>  

2.  <%  

3.  String path = request.getContextPath();  

4.  String basePath =  

5.  request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  

6.  %>  

7.  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  

8.  <html>  

9.  <head>  

10. <base href="<%=basePath%>">  

11. <title>出錯了!</title>  

12. </head>  

13. <body>  

14. 出錯了!<br/>  

15. 詳細信息是:<br/>  

16. ${message}<br/><br/>  

17. <a href="javascript:history.back();" mce_href="javascript:history.back();">返回</a>  

18. </body>  

19. </html>  

 

(6)form.js

1.  // 驗證表單輸入不爲空的腳本代碼   

2.  function checkForm(form) {  

3.      if (form.bookname.value == "") {  

4.          alert("書名不能爲空!");  

5.          form.bookname.focus();  

6.          return false;  

7.      }  

8.      if (form.bookauthor.value == "") {  

9.          alert("作者不能爲空!");  

10.         form.bookauthor.focus();  

11.         return false;  

12.     }  

13.     if (form.bookprice.value == "") {  

14.         alert("價格不能爲空!");  

15.         form.bookprice.focus();  

16.         return false;  

17.     }  

18.     return true;  

19. }  

20. function checkSearchForm(form){  

21.     if(form.bookname.value.match(/^/s*$/)){  

22.         alert("查詢條件不能爲空!");  

23.         form.bookname.focus();  

24.         return false;  

25.     }  

26.     return true;  

27. }  

3.公用類及其javabean

(1)EncodingFilter.java(過濾器)

1.  package filter;  

2.  import java.io.IOException;  

3.  import javax.servlet.Filter;  

4.  import javax.servlet.FilterChain;  

5.  import javax.servlet.FilterConfig;  

6.  import javax.servlet.ServletException;  

7.  import javax.servlet.ServletRequest;  

8.  import javax.servlet.ServletResponse;  

9.  public class EncodingFilter implements Filter {  

10.     protected FilterConfig config;  

11.     protected String Encoding = null;  

12.     public void init(FilterConfig config) throws ServletException {  

13.         this.config = config;  

14.         this.Encoding = config.getInitParameter("Encoding");  

15.     }  

16.     public void doFilter(ServletRequest request, ServletResponse response,  

17.             FilterChain chain) throws IOException, ServletException {  

18.         if (request.getCharacterEncoding() == null) {  

19.             if (Encoding != null) {  

20.                 request.setCharacterEncoding(Encoding);  

21.                 response.setCharacterEncoding(Encoding);  

22.             }  

23.         }  

24.         chain.doFilter(request, response);  

25.     }  

26.     public void destroy() {  

27.     }  

28. }  

 

(2)book.java

1.  package dao;  

2.  /** 

3.   * Book entity. @author MyEclipse Persistence Tools 

4.   */  

5.  public class Book implements java.io.Serializable {  

6.      // Fields   

7.      private Integer id;  

8.      private String bookname;  

9.      private String bookauthor;  

10.     private Float bookprice;  

11.     // Constructors   

12.     /** default constructor */  

13.     public Book() {  

14.     }  

15.     /** full constructor */  

16.     public Book(String bookname, String bookauthor, Float bookprice) {  

17.         this.bookname = bookname;  

18.         this.bookauthor = bookauthor;  

19.         this.bookprice = bookprice;  

20.     }  

21.     // Property accessors   

22.     public Integer getId() {  

23.         return this.id;  

24.     }  

25.     public void setId(Integer id) {  

26.         this.id = id;  

27.     }  

28.     public String getBookname() {  

29.         return this.bookname;  

30.     }  

31.     public void setBookname(String bookname) {  

32.         this.bookname = bookname;  

33.     }  

34.     public String getBookauthor() {  

35.         return this.bookauthor;  

36.     }  

37.     public void setBookauthor(String bookauthor) {  

38.         this.bookauthor = bookauthor;  

39.     }  

40.     public Float getBookprice() {  

41.         return this.bookprice;  

42.     }  

43.     public void setBookprice(Float bookprice) {  

44.         this.bookprice = bookprice;  

45.     }  

46. }  

 

4.DAO

BookDAO.java

1.  package dao;  

2.  import java.util.List;  

3.  import org.hibernate.LockMode;  

4.  import org.hibernate.Query;  

5.  import org.slf4j.Logger;  

6.  import org.slf4j.LoggerFactory;  

7.  import org.springframework.context.ApplicationContext;  

8.  import org.springframework.context.support.ClassPathXmlApplicationContext;  

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

10. import org.springframework.transaction.annotation.Transactional;  

11. /** 

12.  * A data access object (DAO) providing persistence and search support for Book 

13.  * entities. Transaction control of the save(), update() and delete() operations 

14.  * can directly support Spring container-managed transactions or they can be 

15.  * augmented to handle user-managed Spring transactions. Each of these methods 

16.  * provides additional information for how to configure it for the desired type 

17.  * of transaction control. 

18.  *  

19.  * @see dao.Book 

20.  * @author MyEclipse Persistence Tools 

21.  */  

22. @Transactional  

23. public class BookDAO extends HibernateDaoSupport {  

24.     private static final Logger log = LoggerFactory.getLogger(BookDAO.class);  

25.     // property constants   

26.     public static final String BOOKNAME = "bookname";  

27.     public static final String BOOKAUTHOR = "bookauthor";  

28.     public static final String BOOKPRICE = "bookprice";  

29.     protected void initDao() {  

30.         // do nothing   

31.     }  

32.     public void save(Book transientInstance) {  

33.         log.debug("saving Book instance");  

34.         try {  

35.             getHibernateTemplate().save(transientInstance);  

36.             log.debug("save successful");  

37.         } catch (RuntimeException re) {  

38.             log.error("save failed", re);  

39.             throw re;  

40.         }  

41.     }  

42.     public void update(Book transientInstance) {  

43.         log.debug("saving Book instance");  

44.         try {  

45.             getHibernateTemplate().update(transientInstance);  

46.             log.debug("save successful");  

47.         } catch (RuntimeException re) {  

48.             log.error("save failed", re);  

49.             throw re;  

50.         }  

51.     }  

52.     public void delete(Book persistentInstance) {  

53.         log.debug("deleting Book instance");  

54.         try {  

55.             getHibernateTemplate().delete(persistentInstance);  

56.             log.debug("delete successful");  

57.         } catch (RuntimeException re) {  

58.             log.error("delete failed", re);  

59.             throw re;  

60.         }  

61.     }  

62.     public Book findById(java.lang.Integer id) {  

63.         log.debug("getting Book instance with id: " + id);  

64.         try {  

65.             Book instance = (Book) getHibernateTemplate().get("dao.Book", id);  

66.             return instance;  

67.         } catch (RuntimeException re) {  

68.             log.error("get failed", re);  

69.             throw re;  

70.         }  

71.     }  

72.     public List findByExample(Book instance) {  

73.         log.debug("finding Book instance by example");  

74.         try {  

75.             List results = getHibernateTemplate().findByExample(instance);  

76.             log.debug("find by example successful, result size: "  

77.                     + results.size());  

78.             return results;  

79.         } catch (RuntimeException re) {  

80.             log.error("find by example failed", re);  

81.             throw re;  

82.         }  

83.     }  

84.     public List findByProperty(String propertyName, Object value) {  

85.         log.debug("finding Book instance with property: " + propertyName  

86.                 + ", value: " + value);  

87.         try {  

88.             String queryString = "from Book as model where model."  

89.                     + propertyName + "like = ";  

90.             return getHibernateTemplate().find(queryString, value);  

91.         } catch (RuntimeException re) {  

92.             log.error("find by property name failed", re);  

93.             throw re;  

94.         }  

95.     }  

96.     public List findByBookname(String  bookname) {  

97.         String sql="from Book where bookname like '%"+bookname+"%'";  

98.         Query query=this.getSession().createQuery(sql);  

99.         return query.list();  

100.       }  

101.       public List findByBookauthor(Object bookauthor) {  

102.           return findByProperty(BOOKAUTHOR, bookauthor);  

103.       }  

104.       public List findByBookprice(Object bookprice) {  

105.           return findByProperty(BOOKPRICE, bookprice);  

106.       }  

107.       public List findAll() {  

108.           log.debug("finding all Book instances");  

109.           try {  

110.               String queryString = "from Book";  

111.               return getHibernateTemplate().find(queryString);  

112.           } catch (RuntimeException re) {  

113.               log.error("find all failed", re);  

114.               throw re;  

115.           }  

116.       }  

117.       public Book merge(Book detachedInstance) {  

118.           log.debug("merging Book instance");  

119.           try {  

120.               Book result = (Book) getHibernateTemplate().merge(detachedInstance);  

121.               log.debug("merge successful");  

122.               return result;  

123.           } catch (RuntimeException re) {  

124.               log.error("merge failed", re);  

125.               throw re;  

126.           }  

127.       }  

128.       public void attachDirty(Book instance) {  

129.           log.debug("attaching dirty Book instance");  

130.           try {  

131.               getHibernateTemplate().saveOrUpdate(instance);  

132.               log.debug("attach successful");  

133.           } catch (RuntimeException re) {  

134.               log.error("attach failed", re);  

135.               throw re;  

136.           }  

137.       }  

138.       public void attachClean(Book instance) {  

139.           log.debug("attaching clean Book instance");  

140.           try {  

141.               getHibernateTemplate().lock(instance, LockMode.NONE);  

142.               log.debug("attach successful");  

143.           } catch (RuntimeException re) {  

144.               log.error("attach failed", re);  

145.               throw re;  

146.           }  

147.       }  

148.       public static BookDAO getFromApplicationContext(ApplicationContext ctx) {  

149.           return (BookDAO) ctx.getBean("BookDAO");  

150.       }  

151.       public static void main(String[] args) {  

152.           ApplicationContext ctx =  

153.           new  

154.           ClassPathXmlApplicationContext("applicationContext.xml");  

155.           BookDAO dao = (BookDAO)ctx.getBean("BookDAO");  

156.           Book book = new Book();  

157.           book.setBookname("數學");  

158.           book.setBookauthor("張三");  

159.           book.setBookprice(12.0f);  

160.           dao.save(book);  

161.           }  

162.   }  

 

5.service

(1)IBookManager.java(接口)

1.  package service;  

2.  import java.util.List;  

3.  import dao.Book;  

4.  public interface IBookManager {  

5.      /** 

6.       * 根據ID查找用戶信息。 

7.       *  

8.       * @param id 

9.       *            用戶編號 

10.      * @return 找到的用戶對象,找不到時返回null 

11.      */  

12.     public Book findById(int id);  

13.     /** 

14.      * 更新用戶對象。 

15.      *  

16.      * @param Book 

17.      *            被更新的用戶 

18.      * @return 更新成功與否 

19.      */  

20.     public boolean update(Book Book);  

21.     public boolean save(Book Book);  

22.     /** 

23.      * 刪除用戶對象。 

24.      *  

25.      * @param Book 

26.      *            被刪除的用戶 

27.      * @return 刪除成功與否 

28.      */  

29.     public boolean delete(Book Book);  

30.     /** 

31.      * 根據用戶名查找用戶。 

32.      *  

33.      * @param username 

34.      *            用戶名 

35.      * @return 包含此用戶名的用戶列表 

36.      */  

37.     public List<Book> findByBookname(String username);  

38.     public List findAll();  

39. }  

 

(2)BookManager.java(實現類)

1.  package service;  

2.  import java.util.List;  

3.  import org.springframework.context.ApplicationContext;  

4.  import org.springframework.context.support.ClassPathXmlApplicationContext;  

5.  import dao.Book;  

6.  import dao.BookDAO;  

7.  public class BookManager implements IBookManager {  

8.      private BookDAO bookdao;  

9.        

10.     public boolean delete(Book book) {  

11.         try {  

12.             bookdao.delete(book);  

13.             return true;  

14.         } catch (Exception e) {  

15.         }  

16.         return false;  

17.     }  

18.     public Book findById(int id) {  

19.         return bookdao.findById(id);  

20.     }  

21.     public List findAll(){  

22.         return bookdao.findAll();  

23.     }  

24.     public List<Book> findByBookname(String bookname) {  

25.         return bookdao.findByBookname(bookname);  

26.     }  

27.     public boolean update(Book Book) {  

28.         try {  

29.             bookdao.update(Book);  

30.             return true;  

31.         } catch (Exception e) {  

32.         }  

33.         return false;  

34.     }  

35.     public boolean save(Book Book){  

36.         try {  

37.             bookdao.save(Book);  

38.             return true;  

39.         } catch (Exception e) {  

40.         }  

41.         return false;  

42.     }  

43.     public dao.BookDAO getBookdao() {  

44.         return bookdao;  

45.     }  

46.     public void setBookdao(dao.BookDAO bookdao) {  

47.         this.bookdao = bookdao;  

48.     }  

49. }  

6.Action處理

(1)BookForm.java

1.  package com.zxc.struts.form;  

2.  import org.apache.struts.action.ActionForm;  

3.  public class BookForm extends ActionForm{  

4.      private int id;  

5.      private String bookname;  

6.      private String bookauthor;  

7.      private float bookprice;  

8.      public int getId() {  

9.          return id;  

10.     }  

11.     public void setId(int id) {  

12.         this.id = id;  

13.     }  

14.     public String getBookname() {  

15.         return bookname;  

16.     }  

17.     public void setBookname(String bookname) {  

18.         this.bookname = bookname;  

19.     }  

20.     public String getBookauthor() {  

21.         return bookauthor;  

22.     }  

23.     public void setBookauthor(String bookauthor) {  

24.         this.bookauthor = bookauthor;  

25.     }  

26.     public float getBookprice() {  

27.         return bookprice;  

28.     }  

29.     public void setBookprice(float bookprice) {  

30.         this.bookprice = bookprice;  

31.     }  

32. }  

 

(2)BookAction.java

1.  /* 

2.   * Generated by MyEclipse Struts 

3.   * Template path: templates/java/JavaClass.vtl 

4.   */  

5.  package com.zxc.struts.action;  

6.  import java.util.List;  

7.  import javax.servlet.http.HttpServletRequest;  

8.  import javax.servlet.http.HttpServletResponse;  

9.  import org.apache.struts.action.ActionForm;  

10. import org.apache.struts.action.ActionForward;  

11. import org.apache.struts.action.ActionMapping;  

12. import org.apache.struts.actions.DispatchAction;  

13. import service.IBookManager;  

14. import com.zxc.struts.form.BookForm;  

15. import dao.Book;  

16. /**  

17.  * MyEclipse Struts 

18.  * Creation date: 10-01-2010 

19.  *  

20.  * XDoclet definition: 

21.  * @struts.action validate="true" 

22.  */  

23. public class BookAction extends DispatchAction {  

24.     private IBookManager bookManager;  

25.     public ActionForward addbook(ActionMapping mapping, ActionForm form,  

26.             HttpServletRequest request, HttpServletResponse response) {  

27.         // TODO Auto-generated method stub   

28.         BookForm bookForm=(BookForm)form;  

29.         Book book=new Book();  

30.         book.setBookname(bookForm.getBookname());  

31.         book.setBookauthor(bookForm.getBookauthor());  

32.         book.setBookprice(bookForm.getBookprice());  

33.         bookManager.save(book);  

34.         return listbook(mapping,form,request,response);  

35.     }  

36.     public ActionForward updatebook(ActionMapping mapping, ActionForm form,  

37.             HttpServletRequest request, HttpServletResponse response) {  

38.         // TODO Auto-generated method stub   

39.         BookForm bookForm=(BookForm)form;  

40.         String id=request.getParameter("id");  

41.         Book book=bookManager.findById(Integer.parseInt(id));  

42.         book.setBookname(bookForm.getBookname());  

43.         book.setBookauthor(bookForm.getBookauthor());  

44.         book.setBookprice(bookForm.getBookprice());  

45.         if(bookManager.update(book)){  

46.             return listbook(mapping,form,request,response);  

47.         }else{  

48.             String message="更新失敗!";  

49.             request.setAttribute("message", message);  

50.             return mapping.findForward("message");  

51.         }  

52.     }  

53.     public ActionForward modifybook(ActionMapping mapping, ActionForm form,  

54.             HttpServletRequest request, HttpServletResponse response) {  

55.         // TODO Auto-generated method stub   

56.         String id=request.getParameter("id");  

57.         Book book=bookManager.findById(Integer.parseInt(id));  

58.         request.setAttribute("book", book);  

59.         return mapping.findForward("edit");  

60.     }  

61.     public ActionForward deletebook(ActionMapping mapping, ActionForm form,  

62.             HttpServletRequest request, HttpServletResponse response) {  

63.         // TODO Auto-generated method stub   

64.         String id=request.getParameter("id");  

65.         Book book=bookManager.findById(Integer.parseInt(id));  

66.         if(bookManager.delete(book)){  

67.             return listbook(mapping,form,request,response);  

68.         }else{  

69.             String message="刪除失敗!";  

70.             request.setAttribute("message", message);  

71.             return mapping.findForward("message");  

72.         }  

73.     }  

74.     public ActionForward listbook(ActionMapping mapping, ActionForm form,  

75.             HttpServletRequest request, HttpServletResponse response) {  

76.         // TODO Auto-generated method stub   

77.         List books=bookManager.findAll();  

78.         request.setAttribute("books", books);  

79.         return mapping.findForward("list");  

80.     }  

81.     public ActionForward searchbook(ActionMapping mapping, ActionForm form,  

82.             HttpServletRequest request, HttpServletResponse response) {  

83.         // TODO Auto-generated method stub   

84.         String bookname=request.getParameter("bookname");  

85.         List books=bookManager.findByBookname(bookname);  

86.         request.setAttribute("books", books);  

87.         return mapping.findForward("list");  

88.     }   

89.     public void setBookManager(IBookManager bookManager) {  

90.         this.bookManager = bookManager;  

91.     }  

92.     public IBookManager getBookManager() {  

93.         return bookManager;  

94.     }  

95. }  

 

7.配置文件

(1)log4j.properties

1.  log4j.rootLogger=WARN, stdout  

2.  log4j.appender.stdout=org.apache.log4j.ConsoleAppender  

3.  log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  

4.  log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n  

 

(2)hibernate.cfg.xml

1.  <?xml version='1.0' encoding='UTF-8'?>  

2.  <!DOCTYPE hibernate-configuration PUBLIC  

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

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

5.  <!-- Generated by MyEclipse Hibernate Tools.                   -->  

6.  <hibernate-configuration>  

7.      <session-factory>  

8.          <property name="dialect">  

9.              org.hibernate.dialect.MySQLDialect  

10.         </property>  

11.         <property name="connection.url">  

12.             jdbc:mysql://localhost:3306/book   

13.         </property>  

14.         <property name="connection.username">root</property>  

15.         <property name="connection.password">123</property>  

16.         <property name="connection.driver_class">  

17.             com.mysql.jdbc.Driver  

18.         </property>  

19.         <property name="myeclipse.connection.profile">mysql5</property>  

20.         <mapping resource="dao/Book.hbm.xml" />  

21.     </session-factory>  

22. </hibernate-configuration>  

 

(3)book.hbm.xml

1.  <?xml version="1.0" encoding="utf-8"?>  

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

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

4.  <!--   

5.      Mapping file autogenerated by MyEclipse Persistence Tools  

6.  -->  

7.  <hibernate-mapping>  

8.      <class name="dao.Book" table="book" catalog="book">  

9.          <id name="id" type="java.lang.Integer">  

10.             <column name="id" />  

11.             <generator class="increment" />  

12.         </id>  

13.         <property name="bookname" type="java.lang.String">  

14.             <column name="bookname" length="30" />  

15.         </property>  

16.         <property name="bookauthor" type="java.lang.String">  

17.             <column name="bookauthor" length="30" />  

18.         </property>  

19.         <property name="bookprice" type="java.lang.Float">  

20.             <column name="bookprice" precision="12" scale="0" />  

21.         </property>  

22.     </class>  

23. </hibernate-mapping>  

 

(4)struts-config.xml

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

2.  <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">  

3.  <struts-config>  

4.      <form-beans>  

5.      <form-bean name="bookForm" type="com.zxc.struts.form.BookForm"/>  

6.      </form-beans>  

7.      <global-exceptions />  

8.      <global-forwards />  

9.      <action-mappings >  

10.     <action  

11.       path="/book"  

12.       name="bookForm"  

13.       parameter="method"  

14.       type="com.zxc.struts.action.BookAction"  

15.       cancellable="true" >  

16.       <forward name="list" path="/list.jsp"/>  

17.       <forward name="edit" path="/edit.jsp"/>  

18.       <forward name="message" path="/error.jsp"/>  

19.     </action>  

20.     </action-mappings>  

21.     <controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor" />  

22.     <message-resources parameter="com.zxc.struts.ApplicationResources" />  

23.     <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">  

24.         <set-property property="contextConfigLocation"  

25.             value="/WEB-INF/classes/applicationContext.xml" />  

26.     </plug-in>  

27. </struts-config>  

(5)applicationContext.xml

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

2.  <beans xmlns="http://www.springframework.org/schema/beans"  

3.      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  

4.      xmlns:tx="http://www.springframework.org/schema/tx"  

5.      xsi:schemaLocation="http://www.springframework.org/schema/beans    

6.      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   

7.      http://www.springframework.org/schema/tx   

8.  http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   

9.      ">  

10.     <tx:annotation-driven transaction-manager="transactionManager"  

11.         proxy-target-class="true" />  

12.     <bean id="sessionFactory"  

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

14.         <property name="configLocation" value="classpath:hibernate.cfg.xml">  

15.         </property>  

16.     </bean>  

17.     <bean id="BookDAO" class="dao.BookDAO">  

18.         <property name="sessionFactory">  

19.             <ref bean="sessionFactory" />  

20.         </property>  

21.     </bean>  

22.     <!-- 聲明一個 Hibernate 3 的事務管理器供代理類自動管理事務用 -->  

23.     <bean id="transactionManager"  

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

25.         <property name="sessionFactory">  

26.             <ref local="sessionFactory" />  

27.         </property>  

28.     </bean>  

29. <!-- book業務處理類-->  

30.     <bean id="bookManager" class="service.BookManager">  

31.         <property name="bookdao">  

32.             <ref local="BookDAO"/>  

33.         </property>  

34.     </bean>  

35.     <bean name="/book" class="com.zxc.struts.action.BookAction">  

36.     <property name="bookManager">  

37.         <ref local="bookManager"/>  

38.     </property>  

39.     </bean>  

40. </beans>  

(6)web.xml

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

2.  <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">  

3.    <servlet>  

4.      <servlet-name>action</servlet-name>  

5.      <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>  

6.      <init-param>  

7.        <param-name>config</param-name>  

8.        <param-value>/WEB-INF/struts-config.xml</param-value>  

9.      </init-param>  

10.     <init-param>  

11.       <param-name>debug</param-name>  

12.       <param-value>3</param-value>  

13.     </init-param>  

14.     <init-param>  

15.       <param-name>detail</param-name>  

16.       <param-value>3</param-value>  

17.     </init-param>  

18.     <load-on-startup>0</load-on-startup>  

19.   </servlet>  

20.   <servlet-mapping>  

21.     <servlet-name>action</servlet-name>  

22.     <url-pattern>*.do</url-pattern>  

23.   </servlet-mapping>  

24.   <!--過濾器 -->  

25.     <filter>  

26.         <filter-name>Filter</filter-name>  

27.         <filter-class>  

28.             filter.EncodingFilter<!-- 過濾器類 -->  

29.         </filter-class>  

30.         <init-param>  

31.             <param-name>Encoding</param-name>  

32.             <param-value>gbk</param-value>  

33.         </init-param>  

34.     </filter>  

35.     <filter-mapping>  

36.         <filter-name>Filter</filter-name>  

37.         <url-pattern>/*</url-pattern>  

38.     </filter-mapping>  

39.   <welcome-file-list>  

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

41.   </welcome-file-list>  

42. </web-app>  

發佈了14 篇原創文章 · 獲贊 6 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章