说来话长,Java已经有一段时间没得到我的宠幸了,几乎都忘了它了,由于最近要去AVON实习,所以重新学了一下Java,并且学习一下Struts,hibernate,Spring,现在谈谈struts和hibernate吧。
这几天看了一下struts的运行机制,MVC架构,重新认识了一下架构,hibernate比想象中的简单,不过struts和hibernate的运行机制和源代码都没仔细研究,就随便调试了一下,先看看能否能实现。
下面简单说一下这个小小程序的条件:
1、mysql5.0 http://www.mysql.org
2、myeclipse6.5 http://www.myeclipseide.com
3、tomcat
传说中的tomcat+ struts+hibernate+mysql的小工程开始噜
一、数据库 建立数据库,admin表,字段id--primary key,字段name,字段password.
二、在myeclipse里new project,J2EE的javaweb工程---Test
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
Session session;
Transaction tx;
public void add(Admin admin) throws HibernateException {
try {
session = HibernateSessionFactory.getSession();
tx = session.beginTransaction();
//Add a new admin
session.save(admin);
tx.commit ();
}catch(HibernateException e){
throw e;
}finally{
if (tx==null) {
tx.rollback();
}
HibernateSessionFactory.closeSession();
}
}
}
再打开com.yourcompany.struts.action下的AddAdminAction.java添加(其中如果有错误选中好按ctrl+shift+o自动添加包)
public class AddAdminAction extends Action {
// --------- Instance Variables
// ---------Methods
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
AddAdminForm addAdminForm = (AddAdminForm) form;
// TODO Add a new admin
Admin admin = new Admin();
admin.setName(addAdminForm.getName ());
admin.setPassword(addAdminForm.getPassword ());
AdminDAOFactory adminDAO = new AdminDAOFactory ();
adminDAO.add(admin);
return mapping.findForward("success");
}
}
public ActionErrors validate(
ActionMapping mapping,
HttpServletRequest request) {
// TODO Auto-generated method stub
ActionErrors errors = new ActionErrors();
Session session = SessionFactory.currentSession();
Transaction tx = session.beginTransaction ();
Query query = session.createQuery("select admin from Admin as admin where admin.name = '" + this.name + "'");
Iterator it = query.iterate ();
if (it.hasNext()){
errors.add ("addAdmin.err.name",new ActionMessage("form.addAdmin.err.name"));
}
tx.commit();
SessionFactory.closeSession ();
return errors;
}
public void reset(ActionMapping mapping, HttpServletRequest request) {
// TODO Auto-generated method stub
this.name=null;
this.password=null;
}
再打开com\yourcompanyname\struts下的ApplicationResource.properties在这里面添加错误信息:
Form.addAdmin.err.name=err
好了,到此项目基本完成了,现在部署项目,然后运行一下,看看结构如何,首先部署一下,运行tomcat