专注于互联网--专注于架构

最新标签
网站地图
文章索引
Rss订阅

首页 »Java教程 » strutshibernate:一个简单的struts hibernate例子以及struts hibernate集成 »正文

strutshibernate:一个简单的struts hibernate例子以及struts hibernate集成

来源: 发布时间:星期四, 2009年1月15日 浏览:14次 评论:0
  最近在学几个常用框架集成下面是个有关struts+hibernate集成例子大家都知道任何个复杂东西都是从简单开始所以我先说个struts+hibernate集成然后再进步了解希望对这方面爱好能有所帮助

  、新建个项目(如ssh)

   2、加入该项目对struts支持就是相关struts包(右击你新建项目->MyEclipse选add struts.........)

   3、添加了对struts支持后然后在struts-config.xml文件里右击新建->form action and jsp选项那样就可以把这 3个文件新建好 register1.jsp,Register1Action.java,Register1Form.java(你可以把这 3个文件发布到tomcat进行测试)测试成功就可以执行下

   4、新建个表sstest表有字段id,username,password,id为主健和自动增1

   5同样思路方法添加对hibernate支持

   6、对新建数据表进行hibernate进行映射,打开myhibernate视图右击你sstest表->选hibernate revers engineering选项然后把Sstest.hbm.xml文件映射到hibernateDao包中同时选中工具 hibernate mapping file..., java data object....., java data access object dao...选项先中这几个文件就可以产生下列几个.java文件:BaseHibernateDAO. ,HibernateSessionFactory ,IBaseHibernateDAO, Sstest,SstestDAO,最后你对你代码进行测试测试成功进行下

   7、好了有关struts和hibernate代码基本上差不好了下面来看直代码代码为蓝色就是集成地方,主要是看Register1Action代码,其它代码都是自动生成

  相关代码如下:

  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.prln("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");
}
//数据daoget思路方法
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;
}
}
如果你觉得你代码自动生成有问题你可以参考下列代码

  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
   .prln("%%%% Error Creating SessionFactory %%%%");
  e.prStackTrace;
 }
  }
  private HibernateSessionFactory {
  }
  public Session getSession throws HibernateException {
    Session session = (Session) threadLocal.get;
  (session null || !session.isOpen) {
  (sessionFactory null) {
  rebuildSessionFactory;
  }
  session = (sessionFactory != null) ? sessionFactory.openSession
   : null;
  threadLocal.(session);
 }
     session;
  }
public void rebuildSessionFactory {
 try {
  configuration.configure(configFile);
  sessionFactory = configuration.buildSessionFactory;
 } catch (Exception e) {
  .err
   .prln("%%%% Error Creating SessionFactory %%%%");
  e.prStackTrace;
 }
}
  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>


0

相关文章

读者评论

发表评论

  • 昵称:
  • 内容: