构建类似Google的聊天室Word下载.docx

上传人:b****5 文档编号:20726231 上传时间:2023-01-25 格式:DOCX 页数:17 大小:95.61KB
下载 相关 举报
构建类似Google的聊天室Word下载.docx_第1页
第1页 / 共17页
构建类似Google的聊天室Word下载.docx_第2页
第2页 / 共17页
构建类似Google的聊天室Word下载.docx_第3页
第3页 / 共17页
构建类似Google的聊天室Word下载.docx_第4页
第4页 / 共17页
构建类似Google的聊天室Word下载.docx_第5页
第5页 / 共17页
点击查看更多>>
下载资源
资源描述

构建类似Google的聊天室Word下载.docx

《构建类似Google的聊天室Word下载.docx》由会员分享,可在线阅读,更多相关《构建类似Google的聊天室Word下载.docx(17页珍藏版)》请在冰豆网上搜索。

构建类似Google的聊天室Word下载.docx

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<

hibernate-configuration>

7<

session-factoryname="

java:

hibernate/SessionFactory"

8<

propertyname="

hibernate.connection.driver_class"

com.mysql.jdbc.Driver<

/property>

9<

hibernate.connection.url"

jdbc:

mysql:

//localhost/test<

10<

hibernate.connection.username"

username<

11<

hibernate.connection.password"

pwd<

12<

hibernate.connection.pool_size"

10<

13<

show_sql"

true<

14<

dialect"

org.hibernate.dialect.MySQLDialect<

15<

hibernate.hbm2ddl.auto"

update<

16<

--Mappingfiles-->

17<

mappingresource="

ChatMessage.hbm.xml"

/>

18<

/session-factory>

19<

/hibernate-configuration>

Tokeepthecodesimple,normallyIadddifferentconfigurationsfordifferentclassesinhibernate.

Whatistheneedofdialectinhibernate:

DatabasesimplementsubtledifferencesintheSQLtheyuse.ThingssuchasdatatypesforexamplevaryacrossdatabasesOrdatabasespecificfunctionality–selectingthetopnrowsisdifferentdependingonthedatabase.Thedialectabstractsthissoyoudon’thavetoworryaboutit.Inshortthedialectpropertyinternallycreatesthehighlyoptimizedqueryforunderlyingdatabase.

Herealso,asyoucansee,IhaveincludedfileChatMessage.hbm.xmlfile.

CodeofChatMessage.hbm.xml:

xmlversion="

1.0"

DOCTYPEhibernate-mappingPUBLIC

-//Hibernate/HibernateMappingDTD3.0//EN"

hibernate-mappingdefault-lazy="

false"

classname="

com.G2.pojo.ChatMessage"

table="

chatmessage"

idname="

id"

type="

long"

column="

Id"

generatorclass="

identity"

/id>

Message"

columnname="

userName"

MsgTime"

20<

colorSelected"

21<

22<

23<

/class>

24<

/hibernate-mapping>

UIPartoftheapplication:

FortheUI,Ihavewrittenlotsofcssclasses,thisisnotpossibletowritecompletecodehere.Pleasecheckthecodefromdownloadlinkprovidedatthebottomofthearticle.

UIofthechatwindowiscreatedtogivethefeeloftheGmailchatapplicationasshowninbelowimage:

Gmaillikechatwindowwithemoticons

Here,findthejavascriptcode,whichisresponsibletosendtheAJAXrequesttotheservlet,andgettingbacktheresponsecode:

scripttype="

text/javascript"

2varuEnteredName=prompt("

PleaseEnterYourName"

3$("

#chat_Header"

).html(uEnteredName);

4$("

#msg"

).focus();

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=$("

23$msgEle.val($msgEle.val()+iconCode);

24var$ele=$("

25$ele.hide();

26

27$msgEle.focus();

30functionsaveChats(){

31varuName=$("

).html();

32if(uName=='

'

){

33alert('

Pleaseenteryourname'

34returnfalse;

35}

36varmsg=$("

).val();

37//varoldMsg=$("

#chat-area"

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$("

).html(data);

52$("

#ChatAtBigScreen"

53document.getElementById('

chat-area'

).scrollTop=document.getElementById('

).scrollHeight;

54document.getElementById('

ChatAtBigScreen'

56});

57returnfalse;

58}

59$('

#msg'

).keyup(function(e){

60

61if(e.keyCode==13){

62saveChats();

63$("

).val('

64}

65});

66<

/script>

Utilityclass,responsibletosavethechatinthedatabaseusinghibernate:

1packagecom.G2.Model;

3importjava.util.ArrayList;

4importjava.util.Iterator;

5importjava.util.List;

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();

20publicstaticvoidsaveChat(ChatMessagechat){

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}

42publicstaticList<

ChatMessage>

getMessages(){

43List<

MessageList=newArrayList<

();

44Sessionsession=null;

45try{

46session=factory.openSession();

47StringSQL_QUERY="

fromChatMessagec"

;

48Queryquery=session.createQuery(SQL_QUERY);

49Iterator<

it=query.iterate();

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}

Asshowninabovecode,toworkwithhibernate,ourapplicationwillneedtoreadtheconfigurationfileofhibernatebybelowlineofcode:

1staticConfigurationcf=newConfiguration().configure();

Now,wewillneedtocreatethesessionobjectfromtheSessionFactoryclass:

1staticSessionFactoryfactory=cf.buildSessionFactory();

2Sessionsession=factory.openSession();

Createtheobjectoftransaction:

1Transactiontx=session.beginTransaction();

Tosavetheobjectinthedatabaseusesave()methodofthetransaction.

Togetthelistofchatmessagesfromthedatabase:

1StringSQL_QUERY="

2Queryquery=session.createQuery(SQL_QUERY);

3Iterator<

Hereobjectoforg.hibernate.Queryiscreatedandusingmethoditerate(),itgivesalltherecordsfromthedatabaseasaobject.(ThatiswhatORM–ObjectRelationMapping)

ServletCode:

1packagecom.G2.servlets;

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;

13importcom.G2.Model.DBManager;

14importcom.G2.pojo.ChatMessage;

15

16publicclassChatProcessextendsHttpServlet{

18@Override

19prot

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 农林牧渔 > 林学

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1