首页 »Java教程 » strutshibernate:一个简单的struts hibernate例子以及struts hibernate集成 »正文
strutshibernate:一个简单的struts hibernate例子以及struts hibernate集成
来源: 发布时间:星期四, 2009年1月15日 浏览:14次 评论:0
最近在学几个常用框架 ![](/icons/37099de.gif) 集成 ![](/icons/37099dou.gif) 下面是 ![](/icons/37099yi.gif) 个有关struts+hibernate ![](/icons/37099de.gif) 集成 ![](/icons/37099de.gif) 例子 ![](/icons/37099dou.gif) 大家都知道 ![](/icons/37099dou.gif) 任何 ![](/icons/37099yi.gif) 个复杂 ![](/icons/37099de.gif) 东西 ![](/icons/37099dou.gif) 都是从简单开始 ![](/icons/37099de.gif) ![](/icons/37099dou.gif) 所以我先说 ![](/icons/37099yi.gif) 个struts+hibernate集成 ![](/icons/37099dou.gif) 然后再进 ![](/icons/37099yi.gif) 步了解 ![](/icons/37099dou.gif) 希望对这方面爱好 ![](/icons/37099de.gif) 能有所帮助 ![](/icons/37099yi.gif) 、新建 ![](/icons/37099yi.gif) 个项目(如ssh) 2、加入该项目对struts ![](/icons/37099de.gif) 支持 ![](/icons/37099dou.gif) 就是相关struts包 ![](/icons/37099dou.gif) (右击你新建 ![](/icons/37099de.gif) 项目->MyEclipse ![](/icons/37099dou.gif) 选add struts.........) 3、添加了对struts支持后 ![](/icons/37099dou.gif) 然后在struts-config.xml文件里右击 ![](/icons/37099dou.gif) 新建->form action and jsp选项 ![](/icons/37099dou.gif) 那样就可以把这 3个文件新建好 register1.jsp,Register1Action.java,Register1Form.java(你可以把这 3个文件发布到tomcat进行测试) ![](/icons/37099dou.gif) 测试成功就可以执行下 ![](/icons/37099yi.gif) 步 4、新建 ![](/icons/37099yi.gif) 个表sstest表 ![](/icons/37099dou.gif) 有字段id,username,password,id为主健和自动增1 5 ![](/icons/37099dou.gif) 同样 ![](/icons/37099de.gif) 思路方法添加对hibernate支持 6、对新建 ![](/icons/37099de.gif) 数据表进行hibernate进行映射,打开myhibernate视图 ![](/icons/37099dou.gif) 右击你sstest表->选hibernate revers engineering选项 ![](/icons/37099dou.gif) 然后把Sstest.hbm.xml文件映射到hibernateDao包中 ![](/icons/37099dou.gif) 同时选中工具 hibernate mapping file..., java data object....., java data access object dao...选项 ![](/icons/37099dou.gif) 先中这几个文件就可以产生下列几个.java文件:BaseHibernateDAO. ,HibernateSessionFactory ,IBaseHibernateDAO, Sstest,SstestDAO,最后你对你 ![](/icons/37099de.gif) 代码进行测试 ![](/icons/37099dou.gif) 测试成功 ![](/icons/37099dou.gif) 进行下 ![](/icons/37099yi.gif) 步 7、好了 ![](/icons/37099dou.gif) 有关struts和hibernate代码基本上差不好了 ![](/icons/37099dou.gif) 下面来看 ![](/icons/37099yi.gif) 直代码 ![](/icons/37099dou.gif) 代码为蓝色 ![](/icons/37099de.gif) 就是集成 ![](/icons/37099de.gif) 地方,主要是看Register1Action代码,其它 ![](/icons/37099de.gif) 代码都是自动生成 ![](/icons/37099de.gif) 相关代码如下: register1.jsp <%@ page language="java" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%> <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%> <html> <head> <title>JSP for Register1Form form</title> </head> <body> <html:form action="/register1"> password : <html:password property="password"/><html:errors property="password"/><br/> username : <html:text property="username"/><html:errors property="username"/><br/> <html:submit/><html:cancel/> </html:form> </body> </html>
Register1Action.java package com.yourcompany.struts.action; import hibernateDao.Sstest; import hibernateDao.SstestDAO; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.hibernate.Transaction; import com.yourcompany.struts.form.Register1Form; public Register1Action extends Action { //数据dao SstestDAO sd; public Register1Action { // TODO Auto-generated constructor stub Sd( SstestDAO ); } public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { Register1Form register1Form = (Register1Form) form;// TODO Auto-generated method stub //输出客户端 用户名 response. CharacterEncoding("GB2312"); .out.pr ln("register1Form.namet"+register1Form.getUsername ); /* * 数据库操作 * */ Sstest st = Sstest ; st. Username(register1Form.getUsername ); st. Password(register1Form.getPassword ); //dao对象 SstestDAO sd = getSd ; Transaction tran = sd.getSession .beginTransaction ; //开始事务 sd.save(st); tran.commit ; //请求转发到success mapping.findForward("success"); } //数据dao get![](/icons/37099dou.gif) 思路方法 public void Sd(SstestDAO sd) { this.sd = sd; } public SstestDAO getSd { sd; } }
Register1Form.java package com.yourcompany.struts.form; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { // TODO Auto-generated method stub null; } public void re (ActionMapping mapping, HttpServletRequest request) { // TODO Auto-generated method stub this.username = "qin"; } public String getPassword { password; } public void Password(String password) { this.password = password; } public String getUsername { username; } public void Username(String username) { this.username = username; } } 如果你觉得你 ![](/icons/37099de.gif) 代码自动生成有问题 ![](/icons/37099de.gif) 话 ![](/icons/37099dou.gif) 你可以参考下列代码 BaseHibernateDAO.java package hibernateDao; import org.hibernate.Session; public BaseHibernateDAO implements IBaseHibernateDAO { public Session getSession { HibernateSessionFactory.getSession ; } } HibernateSessionFactory.java package hibernateDao; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; public HibernateSessionFactory { private String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; private final ThreadLocal<Session> threadLocal = ThreadLocal<Session> ; private Configuration configuration = Configuration ; private org.hibernate.SessionFactory sessionFactory; private String configFile = CONFIG_FILE_LOCATION;
{ try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory ; } catch (Exception e) { .err .pr ln("%%%% Error Creating SessionFactory %%%%"); e.pr StackTrace ; } } private HibernateSessionFactory { } public Session getSession throws HibernateException { Session session = (Session) threadLocal.get ; (session null || !session.isOpen ) { (sessionFactory null) { rebuildSessionFactory ; } session = (sessionFactory != null) ? sessionFactory.openSession![](/icons/37099kh.gif) : null; threadLocal. (session); } session; } public void rebuildSessionFactory { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory ; } catch (Exception e) { .err .pr ln("%%%% Error Creating SessionFactory %%%%"); e.pr StackTrace ; } } public void closeSession throws HibernateException { Session session = (Session) threadLocal.get ; threadLocal. (null); (session != null) { session.close ; } } public org.hibernate.SessionFactory getSessionFactory { sessionFactory; } public void ConfigFile(String configFile) { HibernateSessionFactory.configFile = configFile; sessionFactory = null; } public Configuration getConfiguration { configuration; } } IBaseHibernateDAO.java package hibernateDao; import org.hibernate.Session; /** * Data access erface for do model * @author MyEclipse Persistence Tools */ public erface IBaseHibernateDAO { public Session getSession ; }
Sstest.java package hibernateDao; ublic Sstest implements java.io.Serializable { // Fields private Integer id; private String username; private String password; // Constructors /** default constructor */ public Sstest { } /** full constructor */ public Sstest(String username, String password) { this.username = username; this.password = password; } // Property accessors public Integer getId { this.id; } public void Id(Integer id) { this.id = id; } public String getUsername { this.username; } public void Username(String username) { this.username = username; } public String getPassword { this.password; } public void Password(String password) { this.password = password; } } SstestDAO.java package hibernateDao; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.LockMode; import org.hibernate.Query; import org.hibernate.criterion.Example; public SstestDAO extends BaseHibernateDAO { private final Log log = LogFactory.getLog(SstestDAO. ); // property constants public final String USERNAME = "username"; public final String PASSWORD = "password"; public void save(Sstest transientInstance) { log.debug("saving Sstest instance"); try { getSession .save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public void delete(Sstest persistentInstance) { log.debug("deleting Sstest instance"); try { getSession .delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public Sstest findById(java.lang.Integer id) { log.debug("getting Sstest instance with id: " + id); try { Sstest instance = (Sstest) getSession .get("hibernateDao.Sstest", id); instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List findByExample(Sstest instance) { log.debug("finding Sstest instance by example"); try { List results = getSession .createCriteria("hibernateDao.Sstest") .add(Example.create(instance)).list ; log.debug("find by example successful, result size: " + results.size ); results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } public List findByProperty(String propertyName, Object value) { log.debug("finding Sstest instance with property: " + propertyName + ", value: " + value); try { String queryString = "from Sstest as model where model." + propertyName + "= ?"; Query queryObject = getSession .createQuery(queryString); queryObject. Parameter(0, value); queryObject.list ; } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List findByUsername(Object username) { findByProperty(USERNAME, username); } public List findByPassword(Object password) { findByProperty(PASSWORD, password); } public List findAll { log.debug("finding all Sstest instances"); try { String queryString = "from Sstest"; Query queryObject = getSession .createQuery(queryString); queryObject.list ; } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public Sstest merge(Sstest detachedInstance) { log.debug("merging Sstest instance"); try { Sstest result = (Sstest) getSession .merge(detachedInstance); log.debug("merge successful"); result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(Sstest instance) { log.debug("attaching dirty Sstest instance"); try { getSession .saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(Sstest instance) { log.debug("attaching clean Sstest instance"); try { getSession .lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } }
Sstest.hbm.xml <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> < name="hibernateDao.Sstest" table="sstest" schema="dbo" catalog="manager"> <id name="id" type="java.lang.Integer"> <column name="id" /> <generator ="increment" /> </id> <property name="username" type="java.lang.String"> <column name="username" length="10" /> </property> <property name="password" type="java.lang.String"> <column name="password" length="20" /> </property> </ > </hibernate-mapping> struts-config.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd"> <struts-config> <data-sources /> <form-beans > <form-bean name="register1Form" type="com.yourcompany.struts.form.Register1Form" /> </form-beans> <global-exceptions /> <global-forwards /> <action-mappings > <action attribute="register1Form" input="/form/register1.jsp" name="register1Form" path="/register1" scope="request" type="com.yourcompany.struts.action.Register1Action"> <forward name="failed" path="/error.jsp" /> <forward name="success" path="/success.jsp" /> </action> </action-mappings> <message-resources parameter="com.yourcompany.struts.ApplicationResources" /> </struts-config>
相关文章
读者评论
发表评论
|
|