ssh+ajax(jQuery)搭建簡單的聊天室

聊天室外觀:
數據庫設計:
create table message(
  id int not null auto_increment,
  studentId varchar not null,//關聯發表者
  msg text not null,//發表內容
  time date,//發表時間
  primary key(id)
);

服務器端處理用戶提交信息以及返回: javascript

若是有用戶提交信息便插入數據,並保存10條記錄,多出的刪除,不斷更新;從數據庫中獲取數據並用字符串形式返回結果。 html


  1. 對應的model:
    public class Message {
    
    	private  Long id;
    	private  Date time;
    	private  String msg;
    	private Student student;
       //..get and set 方法省略
    }
    //對應的xml
    
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC
            "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
            "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping package="com.ec.model">
    	<class name="Message">
    		<id name="id" type="long">
    			<generator class="native"></generator>
    		</id>
    		<property name="msg" type="text" column="msg"></property>
    		<property name="time" type="date" column="time"></property>
            <many-to-one name="student" column="studentId" class="Student"></many-to-one>
    	
    	</class>
    </hibernate-mapping>
  2. dao層:
    //獲取前幾條舊的聊天記錄,是按id排列的
     public List<Message> getFrontNum(int number) {
    
    
     List<Message> messages = (List<Message>) this.getHt().find("From Message m ").subList(0, number+1);
     return messages;
     }
  3. sevice層:
    //併發問題,兩個同時插入
    	public boolean checkNumAndDel() {
    		
    		int number = this.getAll().size();
    		if(number >= 10){
    			//獲取超過9條的舊記錄,刪除超過的舊記錄
                number = number - 10;
    			List<Message> ms = this.messageDao.getFrontNum(number);
    			for(int i=0;i< ms.size();i++)
    			{
    				this.delete(ms.get(i).getId());
    			}
    			
    		}
    		number = this.getAll().size();
    		return (number < 10);
    		
    	}
  4. action層:
    //timestamp=0第一次獲取聊天記錄,不等於0,不斷更新聊天內容
    public String saveUI()
    	{
    		if(this.timestamp == 0){
    			
    			List<Message> messages = this.messageService.getAll();
    			ActionContext.getContext().put("messages", messages);
    			return "saveUI";
    		}else{
    			List<Message> messages = this.messageService.getAll();
    			for(int i =0 ;i<messages.size();i++)
    			{
    			    String name = this.studentService.getById(messages.get(i).getId()).getName();
    				this.message= name+","+messages.get(i).getMsg()+","+messages.get(i).getTime()+"/";
    			}
    			return SUCCESS;
    		}
    
    		
    	}
    //保存聊天記錄,插入數據以前判斷是否超過10條記錄,作相應的處理	
    	public String save() throws IOException
    	{
    	
    		Student student = (Student)ActionContext.getContext().getSession().get("student");
    		Message msg = new Message();
    		msg.setMsg(getModel().getMsg());
    		msg.setStudent(student);
    		msg.setTime(new Date());
    		if(student==null){
    			System.out.println("你還沒登陸!");
    		}else{
    			
    			if(this.messageService.checkNumAndDel())
    			{
    				this.messageService.add(msg);
    				this.message= student.getName()+","+msg.getMsg()+","+msg.getTime();//"逗號,/是在前端進行分割聊天記錄"
    			
    			}
    		}
    		return SUCCESS;
    	}//struts.xml配置文件以下:
    
        <package name="ajax" extends="json-default">
    
              <action name="ajaxMessage_*" class="messageAction" method="{1}">
              	<result type="json">
              
              	</result>
              </action>
        </package>



客戶端的處理


  1. 提交聊天記錄,而後服務器端保存數據,並返回聊天記錄,呈如今頁面上:HtMl代碼:
    <form id="chatform">
            <div class="ItemBlock_Title1"><!-- 信息說明<DIV CLASS="ItemBlock_Title1">
            	<IMG BORDER="0" WIDTH="4" HEIGHT="7" SRC="../style/blue/images/item_point.gif" /> 信息內容 </DIV>  -->
            </div>
            
            <!-- 表單內容顯示 -->
            <div class="ItemBlockBorder">
                <div class="ItemBlock">
                    <p id="messagewindow">
                      <s:iterator value="messages">
                        <s:if test="#messages.size()>0">
                          <strong>${student.name }</strong>:${msg }------${time }<br/>
                        </s:if>
                        <s:else>
                          <strong>最近沒聊啥!你起個頭吧!</strong>
                        </s:else>
                      </s:iterator>
                      <span id="loading">加載中...</span>
                    </p>
                    <table cellpadding="0" cellspacing="0" class="mainForm">
                        <tr>
                            <td>內容</td>
                            <td><textarea id="msg" name="content" class="TextareaStyle" style="width: 550px; height: 20px;"></textarea></td>
                        </tr>
                    </table>
                </div>
            </div>
            
            <!-- 表單操做 -->
            <div id="InputDetailBar">
    			<input type="IMAGE" src="../style/blue/images/button/send.png"/>
    			<a href="javascript:history.go(-1);"><img src="../style/images/goBack.png"/></a>
            </div>
        </form>
    
       <script type="text/javascript">
         $(function(){
             var timestamp = 0;
             updateMsg();
       	     $("#chatform").submit(function(){
       	  
    	            $.post("ajaxMessage_save.action",{
    	                    msg:$("#msg").val()
    	                },function(data){
    
    	                	$("#msg").val("");//清空信息文本框
    	                	addMessages(data);//調用解析xml的函數
    	                },"json");
    	            return false;//阻止表單提交
    	          });
    
       	       
             }   );
    
         function updateMsg(){
             timestamp = 1;
             $.post("ajaxMessage_saveUI.action",{timestamp:timestamp},function (data){
                 $("#loading").remove();
                 
             });
             setTimeout('updateMsg()',4000);
                
             }
            function addMessages(data){
    
                 var data = eval(data);
                  var message = data["message"];
                  var htmlcode = "";
    
    //根據/分割Message
    ms = message.substring(0,message.length).split("/"); for(var i=0;i<ms.length;i++) { var m = ms[i].split(","); htmlcode="<strong>"+m[0]+"</strong>:"+m[1]+"---"+m[2]+"<br/>"; } $("#messagewindow").append(htmlcode); } </script>
  2. 瀏覽器每隔一段時間更新數據(上面javascript的updateMsg函數)
相關文章
相關標籤/搜索