利用MyEclipse开发Struts+Hibernate的应用 |
利用MyEclipse开发Struts+Hibernate应用 点击下载 其中文章中有个小的错误: VipService.java中所有关闭session的地方有个小问题,还是需要通过SessionFactory来关闭。 } |
转载麻烦署上俺的名字:小兵 个人主页:www.xiebing.com 本文主要使用MyEclipse来开发整合了Struts和Hibernate的应用,重点在于对二者MyEclipse提供支持的工具的使用,如果对于Struts和Hibernate还没有了解的朋友,建议先了解一些Struts和Hibernate的相关概念。 1、首先新建一个J2EE的Web Project,具体的设置如图所示: 点击,完成,完成新建项目。 2、在mydb项目上点击右键,选择MyEclipse选项,为该项目增加Struts的特性。 弹出如下窗口,具体配置,如图所示: 只需修改包的名称,本例中修改为:com.xiebing.struts ,其他保持默认即可。点击完成,MyEclipse就会自动将Struts应用所需要的jar包和自定义标签文件,以及struts的配置文件和资源文件拷贝或创建到相应的目录。 3、创建数据库 在MySQL的test的数据库中创建表: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、打开MyEclipse Database Explorer视图,创建一个数据库的连接: 新建一个数据库连接: 在新的数据库连接的配置窗口中,填写如下配置: 其中Driver的配置,通过 窗口-首选项 MyEclipse Database Explorer Drivers来配置,如下图所示: 点击Edit按钮,对该选项进行配置,配置细节如下,Extra Class Path 要选中一个MySQL的JDBC驱动: 在DB Browser的窗口中连接数据库,连接成功后如图所示: 5、重新切换到MyEclipse视图,在项目上点击右键选择MyEclipse选项,为应用增加Hibernate特性,如图所示: 在出现的配置窗口中,选中“Add Hibernate 2.1 libraries to project?”,然后设定存放Hibernate库文件的目录为: /WEB-INF/lib 目录,默认会选择创建一个新的Hibernate配置文件hibernate.cfg.xml。 点击下一步,进入下面的Hibernate数据库连接配置界面,在Connection Profile选项中直接选择在MyEclipse Database Explorer中配置的vipdata选项,然后就会自动生成其他的配置,可以选择“Copy JDBC Driver and add to classpath”,这样就会将JDBC驱动拷贝到WEB-INF/lib目录中。: 点击下一步,来创建Hibernate的SessionFactory类,这是一个简单的集中管理Hibernate会话的工厂类,填写类的全名称。 点击完成,然后MyEclipse就会将Hibernate相关的jar包拷贝到lib目录下,同时会生成Hibernate的配置文件:hibernate.cfg.xml,和SessionFactory类(改类在下面我会给出简单说明)。 现在要利用MyEclipse Database Explorer视图中的工具来生成,Hibernate的映射文件。切换到MyEclipse Database Explorer视图,在表vipdata上点击右键,选择Create Hibernate Mapping,如图所示: 弹出如下配置界面,配置生成的持久化类和映射文件。 点击Browse,选择生成的类和映射文件的包:com.xiebing.hibernate ID Generator选项,选择native。(还有很多其他的选项可选,根据应用的需要具体选择), 点击完成,这样会生成持久化类Vipdata和它的父类AbstractVipdata(生成父类,有利于日后应用的扩展,工具会自动生成详细的equals方法和hashCode方法)以及映射文件Vipdata.hbm.xml。同时会修改Hibernate的配置文件hibernate.cfg.xml,会增加一行: <mapping resource="com/xiebing/hibernate/Vipdata.hbm.xml"/> 6、使用MyEclipse Struts Editor打开Struts的配置文件:struts-config.xml,并切换到design面板。 选择面板上的Add Jsp Page标签,单击,我们来新建一个jsp页面。然后到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</title> <html:base/> </head> <body bgcolor="white"> <h3>Vip Example</h3> <html:errors/> <% /* * 这里将产生一个Vipdata的集合 */ List vipList = VipService.getInstance().getVipdataList(); request.setAttribute("vipdatas", vipList); %> <p>列出 <code>Vipdata</code>表中的所有信息.</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" /></td> <td><bean:write name="element" property="vipTitle" /></td> </tr> </logic:iterate> </table> <p>新增加一条数据:</p> <html:form action="AddVipdata.do" method="post"> <table border=1> <tr><td>name:</td><td><html:text property="vipName" /></tr> <tr><td>description:</td><td><html:text property="vipTitle" /></td></tr> </table><br/> <html:submit/> </html:form> </body> </html:html>阿飞发送多幅发送给扶绥多给 此时加粗的部分会提示有问题(先不管他),因为还没有创建类:com.xiebing.hibernate.VipService 7、接下来就创建类:com.xiebing.hibernate.VipService。其主要就是完成我们的增删改查等具体业务逻辑的处理。 代码如下: 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; /** * 通过Hibernate来操作数据库的业务逻辑类 * */ public class VipService { private static VipService instance = null; private VipService() { } /** * 得到VipService的单态实例 * @return <code>VipService</code> singleton. */ public static synchronized VipService getInstance() { if (instance == null) { instance = new VipService(); } return instance; } /** * 通过id来获得Vipdata * @param id * @return Vipdata */ public Vipdata getVipdata(Long id) { Session session = null; try { //通过SessionFactory创建session实例 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 { //关闭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(); //创建一条HQL查询 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、顺便简单说一下工具自动生成的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对象为单态 * 初始化一个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 { //多线程情况下共享数据库链接是不安全的。ThreadLocal保证了每个线程都有自己的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(); } } //创建一个数据库连接实例 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文件的编辑界面,通过大纲视图选择action-mappings,点击右键-New Form,Action and JSP:
首先是创建FormBean的配置信息,具体配置如图,同时添加vipname和viptitle两个String类型的属性:
点击下一步进入Action的配置,如图所示:
切换Optional Details的标签到Forwards,加入success的跳转到AddVipData.jsp页面:
具体设置如图:
设置好了以后单击 完成,这样就完成了Struts中的FormBean 和Action的创建。
在struts-config.xml的编辑界面中,出现如下图所示图片:
可以清楚的看到jsp 、form 、action之间的关系。
10、修改struts的资源文件com.xiebing.struts.ApplicationResources的内容为:
errors.footer=</UL><HR>
errors.header=<H3><FONT color="red">Validation Error</FONT></H3>You must correct the following error(s) before proceeding:<UL>
error.vipname.required=<LI>Need a vipname</LI>
error.viptitle.required=<LI>Need a viptitle</LI>
11、接下来修改action类:AddVipdata,和Formbean类:VipdataForm修改后的代码如下:
com.xiebing.action.AddVipdata类
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;
}
}
至此,所以的编码工作已经全部完成,接下来要用MyEclipse来发布web应用
12、点击发布J2EE应用的工具栏图标:
弹出如下界面,点击Add按钮:
在接下来的窗口中,Server选择配置好的服务器,我这里选择:Tomcat5,然后点击完成.这样我们就完成了程序的发布,很简单,也很方便.
然后启动Tomcat5来运行我们的程序:
之后就可以通过浏览器来访问我们的程序了.还不赶快点呀!