Ajax技术--实时显示聊天内容($.post(url,data,success()))

来源:互联网 发布:2017手机淘宝修改差评 编辑:程序博客网 时间:2024/06/05 19:09


聊天内容最新消息出现在最上方。

1、index.jsp页面:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><script type="text/javascript" src ="js/jquery-3.1.1.min.js"></script><script type="text/javascript">   function getContent(){      $.get("ChatServlet?action=get&nocache"+new Date().getTime(),function(data){        $("#div1").html(data);        //$("#div1").text(data);  区别在于显示纯文本和识别html标签      })   }      $(document).ready(function(){     getContent();     setInterval("getContent()",1000);  //必须加引号   });      $(document).ready(function(){     $("#btn").click(function(){       if($("#user").val() != ""){         if($("#speak").val() != ""){            $.post("ChatServlet?action=send",{  //$.post(url,data,success())方法           user:$("#user").val(),           speak:$("#speak").val()});                                 $("#speak").val("") ; //清空说话文本内容           $("#speak").focus();                    }else {           alert("说话内容不能为空");         }       }else {        alert("用户名不能为空");       }     });   });      </script>  </head>        <body>    <div id = "div1" style = "height: 135px;background:red ;overflow:hidden"> 欢迎光临阿文聊天室</div>      <form action="" method = "post" name = "form1">      <input name = "user" type = "text" size = "20" id = "user">说:      <input name = "speak" type = "text" size = "50" id = "speak">        <input name = "btn" type = "button" id = "btn" value ="发送">         </form>      </body></html>

2、一个名为ChatServlet的Servlet

package servlet;import java.io.IOException;import java.io.PrintWriter;import java.util.Date;import java.util.Vector;import javassist.expr.Instanceof;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@SuppressWarnings("serial")public class ChatServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String args = request.getParameter("action");if(args.equals("get")){get(request, response);}else if(args.equals("send")){send(request, response);}}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {            doGet(request, response);}  public void get(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{response.setContentType("text/html;charset=utf-8");response.setHeader("Cache-Control", "no-cache");PrintWriter out = response.getWriter();ServletContext application = getServletContext();String msg = "";if(null != application.getAttribute("massage")){//@SuppressWarnings("unchecked")Vector<String> vec = (Vector<String>)application.getAttribute("massage");for (int i = vec.size() -1; i >= 0; i--) {msg += "<br>"+vec.get(i);}}else{msg = "欢迎光临阿文聊天室";}out.println(msg);}@SuppressWarnings("unchecked")public void send(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{response.setContentType("text/html;charset=utf-8");        ServletContext application = getServletContext();String user = request.getParameter("user");String speak = request.getParameter("speak");String msg = "["+user+"]说:"+speak;Vector<String> vec = (Vector<String>)application.getAttribute("massage");if(vec == null){vec = new Vector<String>();}vec.add(msg);application.setAttribute("massage", vec);//request.getRequestDispatcher("ChatServlet?action=get&nocache"+new Date().getTime()).forward(request, response);}}

分析:同过$.post()和$.get()共同实现,完成无刷新页面与服务器的交互;$.post()将数据传输至Servlet类,由send()函数接受处理,并保存至application对象。设置定时器通过$.get()从Servlet中的get()方法获取保存在application上的数据对象,通过回调函数在div中显示