轉載麻煩署上俺的名字:小兵 個(gè)人主頁(yè):www.xiebing.com
本文主要使用MyEclipse來(lái)開(kāi)發(fā)整合了Struts和Hibernate的應用,重點(diǎn)在于對二者MyEclipse提供支持的工具的使用,如果對于Struts和Hibernate還沒(méi)有了解的朋友,建議先了解一些Struts和Hibernate的相關(guān)概念。
1、首先新建一個(gè)J2EE的Web Project,具體的設置如圖所示:

點(diǎn)擊,完成,完成新建項目。
2、在mydb項目上點(diǎn)擊右鍵,選擇MyEclipse選項,為該項目增加Struts的特性。

彈出如下窗口,具體配置,如圖所示:

只需修改包的名稱(chēng),本例中修改為:com.xiebing.struts ,其他保持默認即可。點(diǎn)擊完成,MyEclipse就會(huì )自動(dòng)將Struts應用所需要的jar包和自定義標簽文件,以及struts的配置文件和資源文件拷貝或創(chuàng )建到相應的目錄。
3、創(chuàng )建數據庫
在MySQL的test的數據庫中創(chuàng )建表:vipdata
DROP TABLE IF EXISTS vipdata;
CREATE TABLE vipdata (
vipId int(11) NOT NULL AUTO_INCREMENT,
vipName varchar(20) NOT NULL,
vipTitle varchar(20) NOT NULL,
PRIMARY KEY (vipId))
TYPE=MyISAM;
4、打開(kāi)MyEclipse Database Explorer視圖,創(chuàng )建一個(gè)數據庫的連接:
新建一個(gè)數據庫連接:

在新的數據庫連接的配置窗口中,填寫(xiě)如下配置:

其中Driver的配置,通過(guò) 窗口-首選項 MyEclipse Database Explorer Drivers來(lái)配置,如下圖所示:

點(diǎn)擊Edit按鈕,對該選項進(jìn)行配置,配置細節如下,Extra Class Path 要選中一個(gè)MySQL的JDBC驅動(dòng):

在DB Browser的窗口中連接數據庫,連接成功后如圖所示:

5、重新切換到MyEclipse視圖,在項目上點(diǎn)擊右鍵選擇MyEclipse選項,為應用增加Hibernate特性,如圖所示:

在出現的配置窗口中,選中“Add Hibernate 2.1 libraries to project?”,然后設定存放Hibernate庫文件的目錄為: /WEB-INF/lib 目錄,默認會(huì )選擇創(chuàng )建一個(gè)新的Hibernate配置文件hibernate.cfg.xml。

點(diǎn)擊下一步,進(jìn)入下面的Hibernate數據庫連接配置界面,在Connection Profile選項中直接選擇在MyEclipse Database Explorer中配置的vipdata選項,然后就會(huì )自動(dòng)生成其他的配置,可以選擇“Copy JDBC Driver and add to classpath”,這樣就會(huì )將JDBC驅動(dòng)拷貝到WEB-INF/lib目錄中。:

點(diǎn)擊下一步,來(lái)創(chuàng )建Hibernate的SessionFactory類(lèi),這是一個(gè)簡(jiǎn)單的集中管理Hibernate會(huì )話(huà)的工廠(chǎng)類(lèi),填寫(xiě)類(lèi)的全名稱(chēng)。

點(diǎn)擊完成,然后MyEclipse就會(huì )將Hibernate相關(guān)的jar包拷貝到lib目錄下,同時(shí)會(huì )生成Hibernate的配置文件:hibernate.cfg.xml,和SessionFactory類(lèi)(改類(lèi)在下面我會(huì )給出簡(jiǎn)單說(shuō)明)。
現在要利用MyEclipse Database Explorer視圖中的工具來(lái)生成,Hibernate的映射文件。切換到MyEclipse Database Explorer視圖,在表vipdata上點(diǎn)擊右鍵,選擇Create Hibernate Mapping,如圖所示:

彈出如下配置界面,配置生成的持久化類(lèi)和映射文件。

點(diǎn)擊Browse,選擇生成的類(lèi)和映射文件的包:com.xiebing.hibernate

ID Generator選項,選擇native。(還有很多其他的選項可選,根據應用的需要具體選擇),

點(diǎn)擊完成,這樣會(huì )生成持久化類(lèi)Vipdata和它的父類(lèi)AbstractVipdata(生成父類(lèi),有利于日后應用的擴展,工具會(huì )自動(dòng)生成詳細的equals方法和hashCode方法)以及映射文件Vipdata.hbm.xml。同時(shí)會(huì )修改Hibernate的配置文件hibernate.cfg.xml,會(huì )增加一行:
<mapping resource="com/xiebing/hibernate/Vipdata.hbm.xml"/>
6、使用MyEclipse Struts Editor打開(kāi)Struts的配置文件:struts-config.xml,并切換到design面板。

選擇面板上的Add Jsp Page標簽,單擊,我們來(lái)新建一個(gè)jsp頁(yè)面。然后到design面板上單擊:

出現如下所示的界面,具體設置如圖所示:

修改AddVipData.jsp的代碼如下:
<%@ page language="java" contentType="text/html; charset=gbk" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-tiles" prefix="tiles" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-template" prefix="template" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-nested" prefix="nested" %>
<%@ page import="com.xiebing.hibernate.VipService" %>
<%@ page import="java.util.List" %>
DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html:html locale="true"> <head> <title>Vip Example< span="">title> <html:base/> < span="">head> <body bgcolor="white"> <h3>Vip Example< span="">h3> <html:errors/> <% /* * 這里將產(chǎn)生一個(gè)Vipdata的集合 */ List vipList = VipService.getInstance().getVipdataList(); request.setAttribute("vipdatas", vipList); %> <p>列出 <code>Vipdata< span="">code>表中的所有信息.< span="">p> <table border=1> <logic:iterate id="element" name="vipdatas" scope="request" type="com.xiebing.hibernate.Vipdata" > <tr> <td><bean:write name="element" property="vipName" />< span="">td> <td><bean:write name="element" property="vipTitle" />< span="">td> < span="">tr> < span="">logic:iterate> < span="">table> <p>新增加一條數據:< span="">p> <html:form action="AddVipdata.do" method="post"> <table border=1> <tr><td>name:< span="">td><td><html:text property="vipName" />< span="">tr> <tr><td>description:< span="">td><td><html:text property="vipTitle" />< span="">td>< span="">tr> < span="">table><br/> <html:submit/> < span="">html:form> < span="">body> < span="">html:html>阿飛發(fā)送多幅發(fā)送給扶綏多給 此時(shí)加粗的部分會(huì )提示有問(wèn)題(先不管他),因為還沒(méi)有創(chuàng )建類(lèi):com.xiebing.hibernate.VipService 7、接下來(lái)就創(chuàng )建類(lèi):com.xiebing.hibernate.VipService。其主要就是完成我們的增刪改查等具體業(yè)務(wù)邏輯的處理。 代碼如下: VipService.java package com.xiebing.hibernate; import java.util.List; import net.sf.hibernate.HibernateException; import net.sf.hibernate.ObjectNotFoundException; import net.sf.hibernate.Query; import net.sf.hibernate.Session; import com.xiebing.hibernate.Vipdata; /** * 通過(guò)Hibernate來(lái)操作數據庫的業(yè)務(wù)邏輯類(lèi) * */ public class VipService { private static VipService instance = null; private VipService() { } /** * 得到VipService的單態(tài)實(shí)例 * @return */ public static synchronized VipService getInstance() { if (instance == null) { instance = new VipService(); } return instance; } /** * 通過(guò)id來(lái)獲得Vipdata * @param id * @return Vipdata */ public Vipdata getVipdata(Long id) { Session session = null; try { //通過(guò)SessionFactory創(chuàng )建session實(shí)例 session = SessionFactory.currentSession(); //調用load方法加載數據 return (Vipdata) session.load(Vipdata.class, id); } catch (ObjectNotFoundException onfe) { return null; } catch (HibernateException e) { System.err.println("Hibernate Exception" + e.getMessage()); throw new RuntimeException(e); } finally { if (session != null) { try { //關(guān)閉session session.close(); } catch (HibernateException e) { System.err.println("Hibernate Exception" + e.getMessage()); throw new RuntimeException(e); } } } } /** * 更新記錄 * * @param vipdata */ public void updateVipdata(Vipdata vipdata) { Session session = null; try { session = SessionFactory.currentSession(); //執行update操作 session.update(vipdata); session.flush(); } catch (HibernateException e) { System.err.println("Hibernate Exception" + e.getMessage()); throw new RuntimeException(e); } finally { if (session != null) { try { session.close(); } catch (HibernateException e) { System.err.println("Hibernate Exception" + e.getMessage()); throw new RuntimeException(e); } } } } /** * 得到所有的記錄 * * @return 記錄的列表 */ public List getVipdataList() { Session session = null; try { session = SessionFactory.currentSession(); //創(chuàng )建一條HQL查詢(xún) Query query = session.createQuery( "select Vipdata from com.xiebing.hibernate.Vipdata Vipdata order by Vipdata.vipname"); return query.list(); } catch (HibernateException e) { System.err.println("Hibernate Exception" + e.getMessage()); throw new RuntimeException(e); } finally { if (session != null) { try { session.close(); } catch (HibernateException e) { System.err.println("Hibernate Exception" + e.getMessage()); throw new RuntimeException(e); } } } } /** * 添加一條新的記錄 * @param data */ public void addVipdata(Vipdata data) { Session session = null; try { session = SessionFactory.currentSession(); session.save(data); session.flush(); } catch (HibernateException e) { System.err.println("Hibernate Exception" + e.getMessage()); throw new RuntimeException(e); } finally { if (session != null) { try { session.close(); } catch (HibernateException e) { System.err.println("Hibernate Exception" + e.getMessage()); throw new RuntimeException(e); } } } } } 8、順便簡(jiǎn)單說(shuō)一下工具自動(dòng)生成的SessionFactory的代碼,SessionFactory.java package com.xiebing.hibernate; import net.sf.hibernate.HibernateException; import net.sf.hibernate.Session; import net.sf.hibernate.cfg.Configuration; public class SessionFactory { private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; /** 保持session對象為單態(tài) * 初始化一個(gè)ThreadLocal對象 * */ private static final ThreadLocal threadLocal = new ThreadLocal(); private static final Configuration cfg = new Configuration(); private static net.sf.hibernate.SessionFactory sessionFactory; /** * Returns the ThreadLocal Session instance. * * @return Session * @throws HibernateException */ public static Session currentSession() throws HibernateException { //多線(xiàn)程情況下共享數據庫鏈接是不安全的。ThreadLocal保證了每個(gè)線(xiàn)程都有自己的s(數據庫連接) Session session = (Session) threadLocal.get(); if (session == null) { if (sessionFactory == null) { try { cfg.configure(CONFIG_FILE_LOCATION); sessionFactory = cfg.buildSessionFactory(); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } //創(chuàng )建一個(gè)數據庫連接實(shí)例 session = sessionFactory.openSession(); //保存該數據庫連接s到ThreadLocal中 threadLocal.set(session); } return session; } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * Default constructor. */ private SessionFactory() { } } 9、切換到struts-config.xml文件的編輯界面,通過(guò)大綱視圖選擇action-mappings,點(diǎn)擊右鍵-New Form,Action and JSP: 首先是創(chuàng )建FormBean的配置信息,具體配置如圖,同時(shí)添加vipname和viptitle兩個(gè)String類(lèi)型的屬性: 點(diǎn)擊下一步進(jìn)入Action的配置,如圖所示: 切換Optional Details的標簽到Forwards,加入success的跳轉到AddVipData.jsp頁(yè)面: 具體設置如圖: 設置好了以后單擊 完成,這樣就完成了Struts中的FormBean 和Action的創(chuàng )建。 在struts-config.xml的編輯界面中,出現如下圖所示圖片: 可以清楚的看到jsp 、form 、action之間的關(guān)系。 10、修改struts的資源文件com.xiebing.struts.ApplicationResources的內容為: errors.footer= errors.header= error.vipname.required= error.viptitle.required= 11、接下來(lái)修改action類(lèi):AddVipdata,和Formbean類(lèi):VipdataForm修改后的代碼如下: com.xiebing.action.AddVipdata類(lèi) package com.xiebing.action; 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 com.xiebing.formbean.VipdataForm; import com.xiebing.hibernate.Vipdata; import com.xiebing.hibernate.VipService; public class AddVipdata extends Action { /** * Method execute * @param mapping * @param form * @param request * @param response * @return ActionForward */ public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { VipdataForm AddVipdataForm = (VipdataForm) form; if (AddVipdataForm.getVipname() != null) { Vipdata vipdata = new Vipdata(); vipdata.setViptitle(AddVipdataForm.getViptitle()); vipdata.setVipname(AddVipdataForm.getVipname()); VipService.getInstance().addVipdata(vipdata); AddVipdataForm.clear(); } return mapping.findForward("success"); } } com.xiebing.formbean.VipdataForm package com.xiebing.formbean; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; public class VipdataForm extends ActionForm { /** vipname property */ private String vipname; /** viptitle property */ private String viptitle; // --------------------------------------------------------- Methods /** * Method validate * @param mapping * @param request * @return ActionErrors */ public ActionErrors validate( ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); if (vipname == null || vipname.length() < 1) { errors.add("vipName", new ActionError("error.vipname.required")); } if (viptitle == null || viptitle.length() < 1) { errors.add("vipTitle", new ActionError("error.viptitle.required")); } return errors; } public void reset(ActionMapping mapping, HttpServletRequest request) { clear(); } public String getVipname() { return vipname; } public void setVipname(String vipname) { this.vipname = vipname; } public String getViptitle() { return viptitle; } public void setViptitle(String viptitle) { this.viptitle = viptitle; } public void clear() { viptitle = null; vipname = null; } } 至此,所以的編碼工作已經(jīng)全部完成,接下來(lái)要用MyEclipse來(lái)發(fā)布web應用 12、點(diǎn)擊發(fā)布J2EE應用的工具欄圖標: 彈出如下界面,點(diǎn)擊Add按鈕: 在接下來(lái)的窗口中,Server選擇配置好的服務(wù)器,我這里選擇:Tomcat5,然后點(diǎn)擊完成.這樣我們就完成了程序的發(fā)布,很簡(jiǎn)單,也很方便. 然后啟動(dòng)Tomcat5來(lái)運行我們的程序:VipService singleton.





Validation Error
You must correct the following error(s) before proceeding:



之后就可以通過(guò)瀏覽器來(lái)訪(fǎng)問(wèn)我們的程序了.還不趕快點(diǎn)呀!
聯(lián)系客服