免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1183 | 回复: 0
打印 上一主题 下一主题

利用MyEclipse开发Struts+Hibernate的应用2[zt] [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2005-08-07 14:40 |只看该作者 |倒序浏览

本文主要使用MyEclipse来开发整合了Struts和Hibernate的应用,重点在于对二者MyEclipse提供支持的工具的使用,如果对于Struts和Hibernate还没有了解的朋友,建议先了解一些Struts和Hibernate的相关概念。
       /**
        * 得到所有的记录
        *
        * @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=
errors.header=Validation ErrorYou must correct the following error(s) before proceeding:
error.vipname.required=Need a vipname
error.viptitle.required=Need a viptitle
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()
              {
                     errors.add("vipName", new ActionError("error.vipname.required"));
              }
              if (viptitle == null || viptitle.length()
              {
                     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来运行我们的程序:

之后就可以通过浏览器来访问我们的程序了.还不赶快点呀!


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/2016/showart_39526.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP