构建类似Google的聊天室Word下载.docx
- 文档编号:20726231
- 上传时间:2023-01-25
- 格式:DOCX
- 页数:17
- 大小:95.61KB
构建类似Google的聊天室Word下载.docx
《构建类似Google的聊天室Word下载.docx》由会员分享,可在线阅读,更多相关《构建类似Google的聊天室Word下载.docx(17页珍藏版)》请在冰豆网上搜索。
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
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 构建 类似 Google 聊天室
![提示](https://static.bdocx.com/images/bang_tan.gif)