构建类似Google的聊天室.docx
- 文档编号:7607975
- 上传时间:2023-01-25
- 格式:DOCX
- 页数:17
- 大小:95.61KB
构建类似Google的聊天室.docx
《构建类似Google的聊天室.docx》由会员分享,可在线阅读,更多相关《构建类似Google的聊天室.docx(17页珍藏版)》请在冰豆网上搜索。
构建类似Google的聊天室
Servlet,Hibernate,jQueryandAjaxbasedgooglelikechat
Hi,Inthisarticle,myaimistocreateanapplicationwhichusestheconceptofHibernateinServletwithAjaxsupportofJquery.
Belowfigurecangiveyoutheideaoffinallookandfeelofthecompleteapplication:
Servlet,Hibernate,jQueryandAjaxbasedgooglelikechat
DataBase:
HereIamusingtheMySQLDatabaseforsavingthemessagesenteredbytheusers:
Copybelowcodetocreatethetableindatabasenamed“test”.
1DROPTABLEIFEXISTS`test`.`chatmessage`;
2CREATETABLE`test`.`chatmessage`(
3`Id`int(10)unsignedNOTNULLAUTO_INCREMENT,
4`Message`varchar(4000)NOTNULL,
5`userName`varchar(100)NOTNULL,
6`MsgTime`varchar(45)NOTNULL,
7`colorSelected`varchar(45)NOTNULL,
8PRIMARYKEY(`Id`)
9)ENGINE=InnoDBAUTO_INCREMENT=400DEFAULTCHARSET=latin1;
Hibernate:
Now,startwiththehibernatepartofthecode.
CreatethePOJO(PlainOldJavaObject),whichmappsthetable“chatmessage”totheobjectinourapplication.
1packagecom.G2.pojo;
2
3importjava.text.DateFormat;
4importjava.text.SimpleDateFormat;
5importjava.util.Date;
6
7publicclassChatMessage{
8privateStringMessage;
9privateStringuserName;
10privateStringMsgTime;
11privateLongId;
12privateStringcolorSelected;
13
14publicStringgetColorSelected(){
15returncolorSelected;
16}
17
18publicvoidsetColorSelected(StringcolorSelected){
19this.colorSelected=colorSelected;
20}
21
22publicStringgetMessage(){
23returnMessage;
24}
25
26publicvoidsetMessage(Stringmessage){
27Message=message;
28}
29
30publicStringgetUserName(){
31returnuserName;
32}
33
34publicvoidsetUserName(StringuserName){
35this.userName=userName;
36}
37
38publicLonggetId(){
39returnId;
40}
41
42publicvoidsetId(Longid){
43Id=id;
44}
45
46publicStringgetMsgTime(){
47DateFormatdateFormat=newSimpleDateFormat("yyyy/MM/ddHH:
mm:
ss");
48Datedate=newDate();
49returndateFormat.format(date);
50}
51
52publicvoidsetMsgTime(StringmsgTime){
53MsgTime=msgTime;
54}
55}
AftercreatingthePOJOclass,createthehibernateconfigurationfile,fromwhichtheapplicationwillcometoknowthathowtomapthetable’scolumnfromdatabasetotheclassmembers,databasenameandsoon.Thehibernateconfigurationfilenamemustbe“hibernate.cfg.xml”anditshouldresideattherootofsourcecode.
Codeofhibernate.cfg.xml:
1
xmlversion='1.0'encoding='utf-8'?
>
2
DOCTYPEhibernate-configurationPUBLIC
3"-//Hibernate/HibernateConfigurationDTD//EN"
4"
5
6
7 hibernate/SessionFactory"> 8 9 mysql: //localhost/test 10 11 12 13 14 15 16 --Mappingfiles--> 17 18 19 Tokeepthecodesimple,normallyIadddifferentconfigurationsfordifferentclassesinhibernate. Whatistheneedofdialectinhibernate: DatabasesimplementsubtledifferencesintheSQLtheyuse.ThingssuchasdatatypesforexamplevaryacrossdatabasesOrdatabasespecificfunctionality–selectingthetopnrowsisdifferentdependingonthedatabase.Thedialectabstractsthissoyoudon’thavetoworryaboutit.Inshortthedialectpropertyinternallycreatesthehighlyoptimizedqueryforunderlyingdatabase. Herealso,asyoucansee,IhaveincludedfileChatMessage.hbm.xmlfile. CodeofChatMessage.hbm.xml: 1 xmlversion="1.0"? > 2 DOCTYPEhibernate-mappingPUBLIC 3"-//Hibernate/HibernateMappingDTD3.0//EN" 4" 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 UIPartoftheapplication: FortheUI,Ihavewrittenlotsofcssclasses,thisisnotpossibletowritecompletecodehere.Pleasecheckthecodefromdownloadlinkprovidedatthebottomofthearticle. UIofthechatwindowiscreatedtogivethefeeloftheGmailchatapplicationasshowninbelowimage: Gmaillikechatwindowwithemoticons Here,findthejavascriptcode,whichisresponsibletosendtheAJAXrequesttotheservlet,andgettingbacktheresponsecode: 1 2varuEnteredName=prompt("PleaseEnterYourName"); 3$("#chat_Header").html(uEnteredName); 4$("#msg").focus(); 5 6functionopenEmot() 7{ 8var$ele=$("#emoticons"); 9varvisibility=$ele.css('display'); 10 11if(visibility=='none') 12{ 13$ele.show(); 14} 15else{ 16$ele.hide(); 17} 18} 19 20functionsmileyCode(iconCode) 21{ 22var$msgEle=$("#msg"); 23$msgEle.val($msgEle.val()+iconCode); 24var$ele=$("#emoticons"); 25$ele.hide(); 26 27$msgEle.focus(); 28} 29 30functionsaveChats(){ 31varuName=$("#chat_Header").html(); 32if(uName==''){ 33alert('Pleaseenteryourname'); 34returnfalse; 35} 36varmsg=$("#msg").val(); 37//varoldMsg=$("#chat-area").html(); 38varcolorCode=$('input[name=nameColor]: checked','#send-message-area') 39.val(); 40 41$.ajax({ 42type: "POST", 43data: "uName="+uName+"&msg="+msg+"&colorCode=" 44+colorCode, 45url: "Chatprocess.do", 46error: function(xhr,ajaxOptions,thrownError){ 47alert(xhr.status); 48alert(thrownError); 49}, 50success: function(data){ 51$("#chat-area").html(data); 52$("#ChatAtBigScreen").html(data); 53document.getElementById('chat-area').scrollTop=document.getElementById('chat-area').scrollHeight; 54document.getElementById('ChatAtBigScreen').scrollTop=document.getElementById('ChatAtBigScreen').scrollHeight; 55} 56}); 57returnfalse; 58} 59$('#msg').keyup(function(e){ 60 61if(e.keyCode==13){ 62saveChats(); 63$("#msg").val(''); 64} 65}); 66 Utilityclass,responsibletosavethechatinthedatabaseusinghibernate: 1packagecom.G2.Model; 2 3importjava.util.ArrayList; 4importjava.util.Iterator; 5importjava.util.List; 6 7importorg.hibernate.Query; 8importorg.hibernate.Session; 9importorg.hibernate.SessionFactory; 10importorg.hibernate.Transaction; 11importorg.hibernate.cfg.Configuration; 12 13importcom.G2.pojo.ChatMessage; 14 15publicclassDBManager{ 16//ReadHibernate.cfg.xml 17staticConfigurationcf=newConfiguration().configure(); 18staticSessionFactoryfactory=cf.buildSessionFactory(); 19 20publicstaticvoidsaveChat(ChatMessagechat){ 21 22Sessionsession=null; 23try{ 24 25session=factory.openSession(); 26Transactiontx=session.beginTransaction(); 27 28session.save(chat); 29mit(); 30 31}catch(Exceptione){ 32e.printStackTrace(); 33}finally{ 34if(session! =null){ 35//Ifacedproblemhere,ifbelowlineisnotwrittenthendataautomaticallygetsdeletedafterinsertion 36session.flush(); 37session.close(); 38} 39} 40} 41 42publicstaticList 43List 44Sessionsession=null; 45try{ 46session=factory.openSession(); 47StringSQL_QUERY="fromChatMessagec"; 48Queryquery=session.createQuery(SQL_QUERY); 49Iterator 50while(it.hasNext()){ 51ChatMessagec=it.next(); 52MessageList.add(c); 53} 54 55}catch(Exceptione){ 56e.printStackTrace(); 57}finally{ 58session.flush(); 59session.close(); 60} 61 62returnMessageList; 63} 64} Asshowninabovecode,toworkwithhibernate,ourapplicationwillneedtoreadtheconfigurationfileofhibernatebybelowlineofcode: 1staticConfigurationcf=newConfiguration().configure(); Now,wewillneedtocreatethesessionobjectfromtheSessionFactoryclass: 1staticSessionFactoryfactory=cf.buildSessionFactory(); 2Sessionsession=factory.openSession(); Createtheobjectoftransaction: 1Transactiontx=session.beginTransaction(); Tosavetheobjectinthedatabaseusesave()methodofthetransaction. Togetthelistofchatmessagesfromthedatabase: 1StringSQL_QUERY="fromChatMessagec"; 2Queryquery=session.createQuery(SQL_QUERY); 3Iterator Hereobjectoforg.hibernate.Queryiscreatedandusingmethoditerate(),itgivesalltherecordsfromthedatabaseasaobject.(ThatiswhatORM–ObjectRelationMapping) ServletCode: 1packagecom.G2.servlets; 2 3importjava.io.IOException; 4importjava.io.PrintWriter; 5importjava.util.HashMap; 6importjava.util.List; 7 8importjavax.servlet.ServletException; 9importjavax.servlet.http.HttpServlet; 10importjavax.servlet.http.HttpServletRequest; 11importjavax.servlet.http.HttpServletResponse; 12 13importcom.G2.Model.DBManager; 14importcom.G2.pojo.ChatMessage; 15 16publicclassChatProcessextendsHttpServlet{ 17 18@Override 19prot
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 构建 类似 Google 聊天室
![提示](https://static.bdocx.com/images/bang_tan.gif)