struts2 Spingr2.5 Hibernate3.3 整合

w768 贡献于2013-08-18

作者 zhaolong  创建于2012-06-05 06:04:00   修改者zhaolong  修改于2012-06-05 09:04:00字数18906

文档摘要:struts2+Spingr2.5+Hibernate3.3整合
关键词:

Java软件工程师实训 张海林 第四课 struts2+Spingr2.5+Hibernate3.3整合 准备数据库和表,以及配置myEclipse的数据库环境 create database mydb go use mydb go create table admin( aid int identity primary key, aname varchar(50), passwd varchar(50) ) -- select * from admin Java软件工程师实训 张海林 一、 在web工程中引入struts2组件包 Java软件工程师实训 张海林 二、 在当前工程引入spring2.5组件包和hibernate3.3组件包 Java软件工程师实训 张海林 Java软件工程师实训 张海林 Java软件工程师实训 张海林 Java软件工程师实训 张海林 Java软件工程师实训 张海林 Java软件工程师实训 张海林 三、 生成pojo和映射文件以及Dao类 Java软件工程师实训 张海林 Java软件工程师实训 张海林 Java软件工程师实训 张海林 Java软件工程师实训 张海林 将dao类移到Dao包 Java软件工程师实训 张海林 package com.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.orm.hibernate3.support.HibernateDaoSupport; import com.po.Admin; /** * A data access object (DAO) providing persistence and search support for Admin * 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 com.po.Admin * @author MyEclipse Persistence Tools Java软件工程师实训 张海林 */ public class AdminDAO extends HibernateDaoSupport { private static final Logger log = LoggerFactory.getLogger(AdminDAO.class); // property constants public static final String ANAME = "aname"; public static final String PASSWD = "passwd"; protected void initDao() { // do nothing } public void save(Admin transientInstance) { log.debug("saving Admin instance"); try { getHibernateTemplate().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public void delete(Admin persistentInstance) { log.debug("deleting Admin instance"); try { getHibernateTemplate().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public Admin findById(java.lang.Integer id) { log.debug("getting Admin instance with id: " + id); try { Admin instance = (Admin) getHibernateTemplate().get("com.po.Admin", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } Java软件工程师实训 张海林 } public List findByExample(Admin instance) { log.debug("finding Admin 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 Admin instance with property: " + propertyName + ", value: " + value); try { String queryString = "from Admin as model where model." + propertyName + "= ?"; return getHibernateTemplate().find(queryString, value); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List findByAname(Object aname) { return findByProperty(ANAME, aname); } public List findByPasswd(Object passwd) { return findByProperty(PASSWD, passwd); } public List findAll() { log.debug("finding all Admin instances"); try { String queryString = "from Admin"; return getHibernateTemplate().find(queryString); } catch (RuntimeException re) { log.error("find all failed", re); throw re; Java软件工程师实训 张海林 } } public Admin merge(Admin detachedInstance) { log.debug("merging Admin instance"); try { Admin result = (Admin) getHibernateTemplate().merge( detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(Admin instance) { log.debug("attaching dirty Admin instance"); try { getHibernateTemplate().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(Admin instance) { log.debug("attaching clean Admin instance"); try { getHibernateTemplate().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public static AdminDAO getFromApplicationContext(ApplicationContext ctx) { return (AdminDAO) ctx.getBean("AdminDAO"); } public int findMaxPage(int psize){ if(psize<1)psize=5; Java软件工程师实训 张海林 int maxrow=0; int maxpage=0; String sql="select count(aid) from Admin"; Query qy=getSession().createQuery(sql); maxrow=Integer.parseInt(qy.list().get(0).toString()); if(maxrow==0){ maxpage=1; }else{ maxpage=maxrow%psize==0?maxrow/psize:maxrow/psize+1; } return maxpage; } public List findAll(int cpage,int psize){ if(psize<1)psize=1; if(cpage<1)cpage=1; int maxpage=findMaxPage(psize); if(cpage>maxpage)cpage=maxpage; int pnum=(cpage-1)*psize; String sql="from Admin"; Query qy=getSession().createQuery(sql); qy.setFirstResult(pnum); qy.setMaxResults(psize); return qy.list(); } } 四、 编写实体类(自己写的Bean类相当于以前的FormBean) (1) 分页显示的实体类PageBean.java package com.bean; import java.util.*; public class PageBean { private int cpage; private int psize; private int maxpage; private List pagelist; public int getCpage() { return cpage; } public void setCpage(int cpage) { this.cpage = cpage; } Java软件工程师实训 张海林 public int getPsize() { return psize; } public void setPsize(int psize) { this.psize = psize; } public int getMaxpage() { return maxpage; } public void setMaxpage(int maxpage) { this.maxpage = maxpage; } public List getPagelist() { return pagelist; } public void setPagelist(List pagelist) { this.pagelist = pagelist; } } 五、 编写业务类 package com.business; import java.util.*; public interface IBusiness { public boolean save(Object ob); public boolean update(Object ob); public boolean delById(int id); public Object findById(int id); public List findAll(); public List findAll(int cpage,int psize); public int findMaxPage(int psize); } AdminBusiness.java package com.business; import java.util.List; import com.dao.*; import com.po.Admin; Java软件工程师实训 张海林 public class AdminBusiness implements IBusiness { private AdminDAO adao; public AdminDAO getAdao() { return adao; } public void setAdao(AdminDAO adao) { this.adao = adao; } public boolean delById(int id) { // TODO Auto-generated method stub Admin admin=adao.findById(id); try { adao.delete(admin); return true; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } public List findAll() { // TODO Auto-generated method stub return adao.findAll(); } public List findAll(int cpage, int psize) { // TODO Auto-generated method stub return adao.findAll(cpage, psize); } public Object findById(int id) { // TODO Auto-generated method stub Admin admin=adao.findById(id); return admin; } public int findMaxPage(int psize) { // TODO Auto-generated method stub return adao.findMaxPage(psize); } Java软件工程师实训 张海林 public boolean save(Object ob) { // TODO Auto-generated method stub Admin admin=(Admin) ob; try { adao.save(admin); return true; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } public boolean update(Object ob) { // TODO Auto-generated method stub Admin admin=(Admin) ob; try { adao.merge(admin); return true; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } } 六、 编写Action类 (1) 编写Action接口IAction.java package com.action; public interface IAction { public String save(); public String update(); public String delById(); public String findById(); public String findAll(); } AdminAction.java package com.action; import java.util.*; Java软件工程师实训 张海林 import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.business.*; import com.bean.*; import com.opensymphony.xwork2.ActionContext; import com.po.Admin; public class AdminAction implements IAction { private Admin admin; private IBusiness abuss; private String aid; private String nextpath; private String page; private String rows; public String getPage() { return page; } public void setPage(String page) { this.page = page; } public String getRows() { return rows; } public void setRows(String rows) { this.rows = rows; } public Admin getAdmin() { return admin; } public void setAdmin(Admin admin) { this.admin = admin; } public IBusiness getAbuss() { return abuss; } Java软件工程师实训 张海林 public void setAbuss(IBusiness abuss) { this.abuss = abuss; } public String getAid() { return aid; } public void setAid(String aid) { this.aid = aid; } public String getNextpath() { return nextpath; } public void setNextpath(String nextpath) { this.nextpath = nextpath; } public String delById() { // TODO Auto-generated method stub boolean bl=abuss.delById(Integer.parseInt(aid)); if(bl){ nextpath="findAll_Admin"; return "delById_Admin_ok"; } return "fail"; } public String findAll() { // TODO Auto-generated method stub HttpSession session=ServletActionContext.getRequest().getSession(); PageBean pb=(PageBean) session.getAttribute("pb"); if(pb==null){ pb=new PageBean(); } if(page==null){ page=""+pb.getCpage(); } if(rows==null){ rows=""+pb.getPsize(); Java软件工程师实训 张海林 } int ps=Integer.parseInt(rows); if(ps<1)ps=5; int maxpage=abuss.findMaxPage(ps); int cp=Integer.parseInt(page); if(cp<1)cp=1; if(cp>maxpage)cp=maxpage; List lsad=abuss.findAll(cp, ps); pb.setCpage(cp); pb.setMaxpage(maxpage); pb.setPagelist(lsad); pb.setPsize(ps); //用于显示下拉列表框的跳转页数 Map map=new HashMap(); for(int i=1;i<=maxpage;i++){ map.put(new Integer(i), ""+i); } session.setAttribute("map", map); session.setAttribute("pb",pb); nextpath="adminlist.jsp"; return "findAll_Admin_ok"; } public String findById() { // TODO Auto-generated method stub admin=(Admin) abuss.findById(Integer.parseInt(aid)); ActionContext.getContext().getSession().put("admin", admin); nextpath="adminupdate.jsp"; return "findById_Admin_ok"; } public String save() { // TODO Auto-generated method stub boolean bl=abuss.save(admin); if(bl){ nextpath="findAll_Admin"; return "save_Admin_ok"; } return "fail"; } public String update() { Java软件工程师实训 张海林 // TODO Auto-generated method stub boolean bl=abuss.update(admin); if(bl){ nextpath="findAll_Admin"; return "update_Admin_ok"; } return "fail"; } } 七、 在applicationContext.xml文件中配置Dao、Business和Action类 org.hibernate.dialect.SQLServerDialect true com/po/Admin.hbm.xml Java软件工程师实训 张海林 八、 配置struuts.xml文件 fail.jsp ${nextpath} 红色部分表示struts的Action对象由spring容器创建。 Java软件工程师实训 张海林 九、 配置web.xml文件,加入spring的配置文件 contextConfigLocation /WEB-INF/applicationContext.xml struts2 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter struts2 /* org.springframework.web.context.ContextLoaderListener index.jsp BASIC 十、 编写页面 (1) index.jap <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% String path = request.getContextPath(); String basePath = re Java软件工程师实训 张海林 quest.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> 增加管理员
增加管理员
账号
密码
 

查看所有

Java软件工程师实训 张海林 (2) adminlist.jsp <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> My JSP 'index.jsp' starting page
显示所有
Java软件工程师实训 张海林
编号 姓名 密码 操作
">删除 ">修改

 

首页 ">上页 ">下页 ">末页 每页 " size="4"> 记录 Java软件工程师实训 张海林

/

返回添加

(3) adminupdate.jsp <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> 修改管理员
修改管理员
账号
密码
 

查看所有

十一、 测试 index.jap Java软件工程师实训 张海林 adminlist.jsp adminupdate.jsp Java软件工程师实训 张海林 修改完成以后 总结 (1) ssh整合和以前的struts1的ssh整合基本相同,当时struts.xml文件的配置一定要正确。Class属性应该是applicationContext.xml文件中配置的bean节点的id属性。 (2) 依赖关系一定要明确 (3) 在引入jar包的时候,一定要引入struts-spring-plugin-xx.jar包,否则,struts将不会被spring代理起来的。 (4) 工程结构如下所示: Java软件工程师实训 张海林

下载文档到电脑,查找使用更方便

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 3 金币 [ 分享文档获得金币 ] 0 人已下载

下载文档