仓酷云
标题:
JAVA网站制作之使用开源项目Hibernate开辟Blog体系
[打印本页]
作者:
老尸
时间:
2015-1-18 11:10
标题:
JAVA网站制作之使用开源项目Hibernate开辟Blog体系
java比较简单,没有C++的烦琐,但学习时最好有C++为基础.与JSP和SQL起应用,功能强大.项目 开辟工具接纳MYECLIPS3.6,起首是创建项目,导进STRUTS+HIBERNATE包,然后设置SRC跟目次下的hibernate.cfg.xml.我接纳的是
MYSQL数据库
,以是设置以下:
<hibernate-configuration>
<session-factory>
<!--properties-->
<propertyname="connection.username">root</property>
<propertyname="connection.url">jdbc:mysql://localhost:3306/tonnyblog</property>
<propertyname="dialect">net.[u]sf[/u].hibernate.dialect.MySQLDialect</property>
<propertyname="connection.password"></property>
<propertyname="connection.driver_class">org.gjt.mm.mysql.Driver</property>
<!--mappingfiles-->
<mappingresource="com/tonny/blog/bean/User.hbm.xml"/>
<mappingresource="com/tonny/blog/bean/Item.hbm.xml"/>
<mappingresource="com/tonny/blog/bean/Review.hbm.xml"/>
</session-factory>
</hibernate-configuration>
复制代码
mapping为JAVABEAN所对应的映照。
上面我们持续HIBERNATE程序的下步编写
importnet.sf.hibernate.HibernateException;
importnet.sf.hibernate.Session;
importnet.sf.hibernate.SessionFactory;
importnet.sf.hibernate.cfg.Configuration;
/**
*DescriptionoftheClass
*
*@authortonny
*@created2004年2月6日
*/
publicclassHibernateUtil{
privatefinalstaticSessionFactorysessionFactory;
static{
try{
sessionFactory=
newConfiguration().configure().buildSessionFactory();
}catch(HibernateExceptionex){
thrownewRuntimeException(
"ExceptionbuildingSessionFactory:"+ex.getMessage(),ex);
}
}
privateHibernateUtil(){
}
/**
*DescriptionoftheField
*/
privatefinalstaticThreadLocalsession=newThreadLocal();
/**
*DescriptionoftheMethod
*
*@returnDescriptionoftheReturnValue
*@exceptionHibernateExceptionDescriptionoftheException
*/
publicstaticSessioncurrentSession()throwsHibernateException{
Sessions=(Session)session.get();
if(s==null){
s=sessionFactory.openSession();
session.set(s);
}
returns;
}
/**
*DescriptionoftheMethod
*
*@exceptionHibernateExceptionDescriptionoftheException
*/
publicstaticvoidcloseSession()throwsHibernateException{
Sessions=(Session)session.get();
session.set(null);
if(s!=null){
s.close();
}
}
publicstaticvoidinit(){
}
}
复制代码
创立sessionFactory
importnet.sf.hibernate.HibernateException;
importnet.sf.hibernate.SessionFactory;
importnet.sf.hibernate.cfg.Configuration;
importorg.apache.struts.action.ActionServlet;
importorg.apache.struts.action.PlugIn;
importorg.apache.struts.config.ModuleConfig;
importcom.tonny.blog.dao.hibernate.HibernateUtil;
publicclassHibernatePluginimplementsorg.apache.struts.action.PlugIn{
publicvoidinit(ActionServletservlet,ModuleConfigconfig){
HibernateUtil.init();
}
publicvoiddestroy(){
try{
HibernateUtil.closeSession();
}
catch(HibernateExceptionhex){
hex.printStackTrace();
}
}
}
复制代码
以上为HIBERNATE基础设置,对数据库操纵接纳DAO形式,增添设置以下:
importcom.tonny.blog.dao.hibernate.*;
publicclassDAOFactory{
privatestaticDAOFactoryinstance;
publicsynchronizedstaticDAOFactorygetInstance(){
if(instance==null){
instance=newDAOFactory();
}
returninstance;
}
privateDAOFactory(){
}
publicItemDAOgetItemDAO(){
returnnewItemDAOHibernate();
}
publicReviewDAOgetReviewDAO(){
returnnewReviewDAOHibernate();
}
publicUserDAOgetUserDAO(){
returnnewUserDAOHibernate();
}
}
复制代码
struts.xml增添设置
<controllercontentType="text/html"debug="3"locale="true"nocache="true"
processorClass="com.tonny.blog.struts.controller.IndexRequestProcessor"/>
<message-resourcesparameter="com.tonny.resource"/>
<[u]plug[/u]-inclassName="com.tonny.blog.struts.plugin.HibernatePlugin"/>
<plug-inclassName="org.apache.struts.tiles.TilesPlugin">
<set-propertyproperty="moduleAware"value="true"/>
<set-propertyproperty="definitions-debug"value="0"/>
<set-propertyproperty="definitions-parser-details"value="0"/>
<set-propertyproperty="definitions-parser-validate"value="false"/>
<set-propertyproperty="definitions-config"value="/WEB-INF/title-def.xml"/>
</plug-in>
复制代码
上面我们界说服务层:
publicclassServiceFactory{
privatestaticServiceFactoryinstance;
publicsynchronizedstaticServiceFactorygetInstance(){
if(instance==null){
instance=newServiceFactory();
}
returninstance;
}
privateServiceFactory(){
}
publicIServicegetService(){
returnnewServiceImp();
}
}
复制代码
importcom.tonny.blog.struts.form.*;
importcom.tonny.blog.view.*;
importcom.tonny.blog.bean.*;
importjava.util.*;
import[u]javax[/u].servlet.http.*;
publicinterfaceIService{
publicUserContainerlogin(UserFormuserForm);
publicbooleanlogout(UserContaineruserContainer);
publicbooleanaddBlog(BlogFormblogForm,StringfilePath);
publicbooleanremoveBlog(Longid);
publicbooleanaddReview(LongtopicId,ReviewFormreviewForm);
publicbooleanupdateBlog(Longid,Stringconten,Stringtopic);
publicbooleanremoveReview(Longid);
public[u]List[/u]getItems();
publicItemViewgetItem(Longid);
publicItemViewgetEditItem(Longid);
publicListsearch(SearchFormsearchForm);
/**
*@paramid
*@paramuserForm
*/
publicbooleanaddUser(UserFormuserForm);
}
复制代码
importcom.tonny.blog.struts.form.*;
importcom.tonny.blog.view.*;
importcom.tonny.blog.dao.*;
importcom.tonny.blog.bean.*;
importjava.util.*;
importjavax.servlet.http.*;
importcom.tonny.blog.struts.util.FileUpload;
publicclassServiceImpimplementsIService{
publicUserContainerlogin(UserFormuserForm){
UserDAOuserDAO=DAOFactory.getInstance().getUserDAO();
Useruser=userDAO.loadUser(userForm.getName());
if(user==null)returnnewUserContainer("",false);
if(!user.getPassword().equals(userForm.getPassword()))returnnewUserContainer("",false);
returnnewUserContainer(userForm.getName(),true);
}
publicbooleanlogout(UserContaineruserContainer){
userContainer.setLogin(false);
userContainer.setName("");
returntrue;
}
publicbooleanaddBlog(BlogFormblogForm,Stringpath){
ItemDAOitemDAO=DAOFactory.getInstance().getItemDAO();
Itemitem=newItem(blogForm.getTopic(),blogForm.getContent(),
FileUpload.upload(blogForm.getFile(),path),newDate());
itemDAO.addItem(item);
returntrue;
}
publicbooleanremoveBlog(Longid){
ReviewDAOreviewDAO=DAOFactory.getInstance().getReviewDAO();
ItemDAOitemDAO=DAOFactory.getInstance().getItemDAO();
itemDAO.removeItem(id);
returnreviewDAO.removeReviews(id);
}
publicbooleanaddReview(LongtopicId,ReviewFormreviewForm){
ReviewDAOreviewDAO=DAOFactory.getInstance().getReviewDAO();
Reviewreview=newReview(reviewForm.getName(),reviewForm.getContent(),
topicId,newDate());
returnreviewDAO.addReview(review);
}
publicbooleanupdateBlog(Longid,Stringcontent,Stringtopic){
ItemDAOitemDAO=DAOFactory.getInstance().getItemDAO();
Itemitem=newItem();
item.setId(id);
item.setContent(content);
item.setTopic(topic);
returnitemDAO.updatItem(item);
}
publicbooleanaddUser(UserFormuserForm){
UserDAOuserDAO=(UserDAO)DAOFactory.getInstance().getUserDAO();
Useruser=newUser(userForm.getName(),userForm.getPassword());
returnuserDAO.addUser(user);
}
publicbooleanremoveReview(Longid){
ReviewDAOreviewDAO=DAOFactory.getInstance().getReviewDAO();
returnreviewDAO.removeReview(id);
}
publicListgetItems(){
ItemDAOitemDAO=DAOFactory.getInstance().getItemDAO();
Listitems=itemDAO.loadItems();
ListitemViews=newArrayList();
for(Iteratorit=items.iterator();it.hasNext();){
Itemitem=(Item)it.next();
ItemViewitemView=newItemView();
itemView.setContent(item.getContent());
itemView.setDate(item.getDate());
itemView.setFile(item.getFile());
itemView.setId(item.getId());
itemView.setTopic(item.getTopic());
itemViews.add(itemView);
}
returnitemViews;
}
publicItemViewgetEditItem(Longid){
ItemDAOitemDAO=DAOFactory.getInstance().getItemDAO();
Itemitem=itemDAO.loadItem(id);
ItemViewitemView=newItemView();
itemView.setContent(item.getContent());
itemView.setDate(item.getDate());
itemView.setFile(item.getFile());
itemView.setId(item.getId());
itemView.setTopic(item.getTopic());
returnitemView;
}
publicListsearch(SearchFormsearchForm){
ItemDAOitemDAO=DAOFactory.getInstance().getItemDAO();
Listitems=itemDAO.loadItems(searchForm.getKeyword());
ListitemViews=newArrayList();
for(Iteratorit=items.iterator();it.hasNext();){
Itemitem=(Item)it.next();
ItemViewitemView=newItemView();
itemView.setContent(item.getContent());
itemView.setDate(item.getDate());
itemView.setFile(item.getFile());
itemView.setId(item.getId());
itemView.setTopic(item.getTopic());
itemViews.add(itemView);
}
returnitemViews;
}
}
复制代码
上面是ACTION怎样挪用以上个服务:
importjava.io.*;
importjavax.servlet.RequestDispatcher;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpSession;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.struts.action.Action;
importorg.apache.struts.action.ActionError;
importorg.apache.struts.action.ActionErrors;
importorg.apache.struts.action.ActionForm;
importorg.apache.struts.action.ActionForward;
importorg.apache.struts.action.ActionMapping;
importorg.apache.struts.action.ActionServlet;
importorg.apache.struts.util.MessageResources;
importcom.tonny.blog.struts.form.*;
publicclassAddBlogextendsBlogBaseAction{
//------------------------------------------------------------LocalForwards
staticfinalprivateStringFORWARD_success="success";
staticfinalprivateStringFORWARD_failure="failure";
//------------------------------------------------------------ActionMethods
publicActionForwardexecute(ActionMappingmapping,ActionFormform,
HttpServletRequestrequest,HttpServletResponseresponse)
throwsException{
if(!isLogin(request))returnmapping.findForward(FORWARD_failure);
service.addBlog((BlogForm)form,((BlogForm)form).getFile().getFileName());
returnmapping.findForward(FORWARD_success);
}
}
复制代码
下一步为DAO层来操纵数据库:
importcom.tonny.blog.bean.*;
importjava.util.List;
publicinterfaceItemDAO{
publicbooleanaddItem(Itemitem);
publicbooleanremoveItem(Longid);
publicListloadItems();
publicListloadItems(Stringtopic);
publicItemloadItem(Longid);
publicbooleanupdatItem(Itemitem);
}
复制代码
DAOFACTORY挪用气力化办法:
importcom.tonny.blog.dao.*;
importnet.sf.hibernate.cfg.Configuration;
importnet.sf.hibernate.*;
importjava.util.*;
importcom.tonny.blog.bean.*;
publicclassItemDAOHibernateextendsDAOHibernateimplementsItemDAO{
publicItemDAOHibernate(){
}
publicbooleanaddItem(Itemitem){
try{
beginTransaction();
session.save(item);
commit();
returntrue;
}
catch(HibernateExceptione){
rollback();
returnfalse;
}
}
publicbooleanupdatItem(Itemitem){
try{
beginTransaction();
Itemit=item;
it=(Item)session.load(Item.class,(item.getId()));
it.setTopic(item.getTopic());
System.out.println("item.getTopic()"+item.getTopic());
it.setContent(item.getContent());
System.out.println("item.getContent()"+item.getContent());
session.flush();
commit();
returntrue;
}
catch(HibernateExceptione){
System.err.println("========>hibernateexception"+e);
rollback();
returnfalse;
}
}
publicbooleanremoveItem(Longid){
try{
beginTransaction();
session.delete("fromcom.tonny.blog.bean.Itemasitemwhereitem.id="+id);
commit();
returntrue;
}
catch(HibernateExceptione){
rollback();
returnfalse;
}
}
publicListloadItems(){
Listlist=null;
try{
beginTransaction();
list=session.find("fromcom.tonny.blog.bean.Itemasitem");
commit();
}
catch(HibernateExceptione){
System.out.println("loadBlogfailed");
rollback();
}
returnlist;
}
publicListloadItems(Stringtopic){
Listlist=null;
try{
beginTransaction();
Queryquery=session.createQuery("fromcom.tonny.blog.bean.Itemasitemwhereitem.topiclike%"+topic+"%");
list=query.list();
commit();
returnlist;
}
catch(HibernateExceptione){
System.out.println("loadblogfailed");
rollback();
}
returnlist;
}
publicItemloadItem(Longid){
Itemitem=null;
try{
beginTransaction();
Queryquery=session.createQuery("fromcom.tonny.blog.bean.Itemasitemwhereitem.id=:id");
query.setLong("id",id.longValue());
Iteratorit=query.iterate();
if(it.hasNext())returnitem=(Item)it.next();
commit();
}
catch(HibernateExceptione){
System.out.println("loadblogfailed");
rollback();
}
returnitem;
}
}
复制代码
这里完成了对数据库查询,修正,删除操纵,没有MANY-TO-MANY操纵。
还是要自己一点一点写代码,然后编译,改错再编译好那。还有最重要的是.net的编译环境非常好,你甚是不需要了解太多工具,对于简单的系统,你可以之了解一些语法就哦了。
作者:
admin
时间:
2015-1-20 15:49
设计模式是高级程序员真正掌握面向对象核心思想的必修课。设计模式并不是一种具体"技术",它讲述的是思想,它不仅仅展示了接口或抽象类在实际案例中的灵活应用和智慧
作者:
飘灵儿
时间:
2015-2-1 23:59
你就该学一学Servlet了。Servlet就是服务器端小程序,他负责生成发送给客户端的HTML文件。JSP在执行时,也是先转换成Servlet再运行的。虽说JSP理论上可以完全取代Servlet,这也是SUN推出JSP的本意,可是Servlet用来控制流程跳转还是挺方便的,也令程序更清晰。接下来你应该学习一下Javabean了,可能你早就看不管JSP在HTML中嵌Java代码的混乱方式了,这种方式跟ASP又有什么区别呢?
作者:
柔情似水
时间:
2015-2-6 19:02
Java自面世后就非常流行,发展迅速,对C++语言形成了有力冲击。Java 技术具有卓越的通用性、高效性、平台移植性和安全性,广泛应用于个人PC、数据中心、游戏控制台
作者:
活着的死人
时间:
2015-2-18 06:47
任职于太阳微系统的詹姆斯·高斯林等人于1990年代初开发Java语言的雏形,最初被命名为Oak,目标设置在家用电器等小型系统的程序语言
作者:
兰色精灵
时间:
2015-3-6 01:03
你一定会高兴地说,哈哈,原来成为Java高手就这么简单啊!记得Tomjava也曾碰到过一个项目经理,号称Java很简单,只要三个月就可以学会。
作者:
若天明
时间:
2015-3-12 18:02
让你能够真正掌握接口或抽象类的应用,从而在原来的Java语言基础上跃进一步,更重要的是,设计模式反复向你强调一个宗旨:要让你的程序尽可能的可重用。
作者:
只想知道
时间:
2015-3-20 01:19
Java 不同于一般的编译执行计算机语言和解释执行计算机语言。它首先将源代码编译成二进制字节码(bytecode),然后依赖各种不同平台上的虚拟机来解释执行字节码。从而实现了“一次编译、到处执行”的跨平台特性。
欢迎光临 仓酷云 (http://ckuyun.com/)
Powered by Discuz! X3.2