分享

SSH实现的增删改查实例

 学习SSH 2012-05-17
一.整合步骤

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事务管理、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(首页)

 
  1. <%@ page language="java" pageEncoding="GBK" %>
  2. <%@ taglib uri="http://struts./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./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. <c:forEach items="${books}" var="book">
  56. <tr>
  57. <td>
  58. ${book.id}
  59. </td>
  60. <td>
  61. ${book.bookname}
  62. </td>
  63. <td>
  64. ${book.bookauthor}
  65. </td>
  66. <td>
  67. ${book.bookprice}
  68. </td>
  69. <td>
  70. <a href="<%=path%>/book.do?method=modifybook&id=${book.id}">修改</a>
  71. <a href="<%=path%>/book.do?method=deletebook&id=${book.id}">删除</a>
  72. </td>
  73. </tr>
  74. </c:forEach>
  75. </table>
  76. </c:when>
  77. <c:otherwise>抱歉,没有找到相关的记录!</c:otherwise>
  78. </c:choose>
  79. <a href="<%=path%>/new.jsp">添加书籍</a>
  80. <form action="<%=path%>/book.do?method=searchbook" method="post" onsubmit="return checkSearchForm(this);">
  81. <fieldset>
  82. <legend>
  83. 查找书籍
  84. </legend>
  85. 书籍名:
  86. <input name="bookname">
  87. <input type="submit" value="查找">
  88. </fieldset>
  89. </form>
  90. </body>
  91. </html>

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

 
  1. <%@ page language="java" pageEncoding="GBK"%>
  2. <%@ taglib uri="http://struts./tags-bean" prefix="bean"%>
  3. <%@ taglib uri="http://struts./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" onsubmit="return checkForm(this);" method="post">
  18. <table width="100%" border="0">
  19. <tbody>
  20. <tr>
  21. <td>
  22. 书籍名:
  23. </td>
  24. <td>
  25. <input name="bookname"/>
  26. <br>
  27. </td>
  28. </tr>
  29. <tr>
  30. <td>
  31. 作者:
  32. </td>
  33. <td>
  34. <input name="bookauthor"/>
  35. </td>
  36. </tr>
  37. <tr>
  38. <td>
  39. 价格:
  40. </td>
  41. <td>
  42. <input name="bookprice"/>
  43. </td>
  44. </tr>
  45. <tr>
  46. <td>
  47. <input type="submit" value="添加" name="button1">
  48. </td>
  49. <td>
  50. <input type="Reset" value="重填" name="button2">
  51. </td>
  52. </tr>
  53. </tbody>
  54. </table>
  55. </form>
  56. <input type="button" onclick="document.location='<%=request.getContextPath()%>/book.do?method=listbook';"
  57. value="
  58. 返回列表">
  59. </body>
  60. </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" onsubmit="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. <input name="bookname" value="${book.bookname}"/>
  25. <br>
  26. </td>
  27. </tr>
  28. <tr>
  29. <td>
  30. 作者:
  31. </td>
  32. <td>
  33. <input name="bookauthor" value="${book.bookauthor}"/>
  34. </td>
  35. </tr>
  36. <tr>
  37. <td>
  38. 价格:
  39. </td>
  40. <td>
  41. <input name="bookprice" value="${book.bookprice}"/>
  42. </td>
  43. </tr>
  44. <tr>
  45. <td>
  46. <input type="submit" value="提交" >
  47. </td>
  48. <td>
  49. <input type="reset" value="重填">
  50. </td>
  51. </tr>
  52. </tbody>
  53. </table>
  54. </form>
  55. <input type="button" onclick="document.location='book.do?method=listbook';" value="返回列表">
  56. </body>
  57. </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. public boolean delete(Book book) {
  10. try {
  11. bookdao.delete(book);
  12. return true;
  13. } catch (Exception e) {
  14. }
  15. return false;
  16. }
  17. public Book findById(int id) {
  18. return bookdao.findById(id);
  19. }
  20. public List findAll(){
  21. return bookdao.findAll();
  22. }
  23. public List<Book> findByBookname(String bookname) {
  24. return bookdao.findByBookname(bookname);
  25. }
  26. public boolean update(Book Book) {
  27. try {
  28. bookdao.update(Book);
  29. return true;
  30. } catch (Exception e) {
  31. }
  32. return false;
  33. }
  34. public boolean save(Book Book){
  35. try {
  36. bookdao.save(Book);
  37. return true;
  38. } catch (Exception e) {
  39. }
  40. return false;
  41. }
  42. public dao.BookDAO getBookdao() {
  43. return bookdao;
  44. }
  45. public void setBookdao(dao.BookDAO bookdao) {
  46. this.bookdao = bookdao;
  47. }
  48. }

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./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./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./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./schema/beans"
  3. xmlns:xsi="http://www./2001/XMLSchema-instance" xmlns:p="http://www./schema/p"
  4. xmlns:tx="http://www./schema/tx"
  5. xsi:schemaLocation="http://www./schema/beans
  6. http://www./schema/beans/spring-beans-3.0.xsd
  7. http://www./schema/tx
  8. http://www./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./xml/ns/javaee" xmlns:xsi="http://www./2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java./xml/ns/javaee http://java./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>

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多