[原]Java web学习系列之 Java web开发中的Struts整合Hibernate
2012-02-28 13:20 雪夜&流星 阅读(257) 评论(0) 编辑 收藏 举报Struts整合Hibernate保存输入数据到数据库中。
配备数据库连接:
接着添加Hibernate架包支持:
接着再添加Struts支持:
创建实体类:
注:该处定要包含有关联的表,不然就会在运行项目的时候出现报错
再就是添加action、form、jsp:
Java web开发是面向对象的编程,故应该将SaveForm中的字段全部封装到对象中去
public class SaveForm extends ActionForm {
//封装对象
private Goods goods=new Goods();
public Goods getGoods() {
return goods;
}
public void setGoods(Goods goods) {
this.goods = goods;
}
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
return null;
}
public void reset(ActionMapping mapping, HttpServletRequest request) {
}
}
DispatchAction类是一个抽象类,它实现了父类(Action)的execute()方法,所以它的子类就不用来实现这个方法了,只需要专注与实际操作的方法
public class SaveAction extends DispatchAction {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
SaveForm saveForm = (SaveForm) form ;
Session session=HibernateSessionFactory.getSession();
session.beginTransaction();
Goods goods=saveForm.getGoods();
session.save(goods);
session.beginTransaction().commit();
session.close();
return mapping.findForward("index");
}
}
对应的save.jsp页面的处理措施为:
<html:form action="/save">
price : <html:text property="goods.price"/><html:errors property="price"/><br/>
goodsName : <html:text property="goods.goodsName"/><html:errors property="goodsName"/><br/>
address : <html:text property="goods.address"/><html:errors property="address"/><br/>
goodsId : <html:text property="goods.goodsId"/><html:errors property="goodsId"/><br/>
state : <html:text property="goods.state"/><html:errors property="state"/><br/>
produceDateTime : <html:text property="goods.produceDatetime"/><html:errors property="produceDateTime"/><br/>
goodsNum : <html:text property="goods.goodsNum"/><html:errors property="goodsNum"/><br/>
quality : <html:text property="goods.quality"/><html:errors property="quality"/><br/>
<html:submit/><html:cancel/>
</html:form>
笔记记于:2010-8-31 20:56