一.整合步骤
1. 通过MyEclipse向导,添加struts功能
2. 通过MyEclipse向导,添加Hibernate3功能:生成会话工厂的那个步骤中一定要将那个对号要去掉,不能由hibernate来生成,而是交给Spring来生成;还有就是导入jar包的时候选择复制到lib目录下这一项。
3. 通过MyEclipse向导,导入实现Spring功能,注意导入jar包的时候选择复制到lib目录下这一项。
3. 利用MyEclipse反向工程的方法,以Spring
4. DAO实现类加入@Transactional标记。
5. 修改applicationContext.xml文件,增加Spring事务管理、DAO等bean的配置。
6. 编写action类。
7. 在applicationContext.xml文件中添加Action的代理bean。
8. 在struts的配置文件中,添加相应的Action,类名指向Spring中的代理bean,并加入
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(首页)
<%@ page language="java" pageEncoding="GBK" %> <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
(2)list.jsp(书籍列表页面)
<%@ 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+"/"; %>
书籍ID | 书籍名称 | 作者 | 价格 | 操作 |
${book.id} | ${book.bookname} | ${book.bookauthor} | ${book.bookprice} | 修改 删除 |
(3)new.jsp(新增书籍页面)
<%@ 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"%>
(4)edit.jsp(书籍修改页面)
<%@ page language="java" pageEncoding="GBK" isELIgnored="false"%>
(5)error.jsp(错误公用页面)
<%@ page language="java" pageEncoding="GBK" isELIgnored="false"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
(6)form.js
// 验证表单输入不为空的脚本代码 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(过滤器)
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
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
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(接口)
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
(2)BookManager.java(实现类)
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
6.Action处理
(1)BookForm.java
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
/* * 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
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
(3)book.hbm.xml
(4)struts-config.xml
(5)applicationContext.xml
(6)web.xml
三.运行效果