- 浏览: 22460 次
- 性别:
- 来自: 天津
最新评论
思想斗争了很久,终于开始接触ajax,作为一个初学者,模仿是个不错的学习方法,至少我是这么学过来的,站长巨人的肩膀上。
这次模仿的内容来自《基于J2EE的Ajax宝典》电子书,在此表示感谢。介绍的是Jsp页面聊天器和ajax聊前器的区别,及ajax的特点体现。
---相对于传统的JSP聊天室而言,Ajax聊天室的速度更快,响应更加流畅。对于复杂页面,Ajax的优势将更加明显:Ajax聊天室只需从服务器获取必须更新的聊天记录,而无须下载整个页面。
Ajax聊天室的最大特点是页面无须刷新,用户感觉不到页面的下载。使用Ajax聊天室时,用户感觉到仿佛在使用普通的Socket聊天室,因为聊天室的页面无须刷新,但用户的聊天信息实时更新。这一切都依赖于Ajax的异步发送请求和动态更新页面。
学习能力自称很强的我,在这下才知道是多么的渺小啊,花了整整一天的时间才得以实现,但这个过程虽败犹荣啊,更深刻的了解了ajax功能实现的整个流程。
1:创建XMLHttpRequest对象
2:取得与服务器的连接(用到post请求)
3:发送post请求时应该增加该文件头
4:指定当XMLHttpRequest状态变化时的处理函数(一个监听的过程)
5:发送请求,及发送信息
-1:这里就是步骤4中的处理函数的书写了
下面贴出ajax聊天器的代码(无数据库)
聊天器聊天界面代码:
有三个控制类处理类(servlet)
1:注册控制处理
2:登陆控制处理类:
3:聊天控制处理类:
然后就是web.xml的配置了
最后就是业务处理了:
至此ajax聊天器的程序测试就这样完成了。
这次模仿的内容来自《基于J2EE的Ajax宝典》电子书,在此表示感谢。介绍的是Jsp页面聊天器和ajax聊前器的区别,及ajax的特点体现。
---相对于传统的JSP聊天室而言,Ajax聊天室的速度更快,响应更加流畅。对于复杂页面,Ajax的优势将更加明显:Ajax聊天室只需从服务器获取必须更新的聊天记录,而无须下载整个页面。
Ajax聊天室的最大特点是页面无须刷新,用户感觉不到页面的下载。使用Ajax聊天室时,用户感觉到仿佛在使用普通的Socket聊天室,因为聊天室的页面无须刷新,但用户的聊天信息实时更新。这一切都依赖于Ajax的异步发送请求和动态更新页面。
学习能力自称很强的我,在这下才知道是多么的渺小啊,花了整整一天的时间才得以实现,但这个过程虽败犹荣啊,更深刻的了解了ajax功能实现的整个流程。
1:创建XMLHttpRequest对象
2:取得与服务器的连接(用到post请求)
3:发送post请求时应该增加该文件头
4:指定当XMLHttpRequest状态变化时的处理函数(一个监听的过程)
5:发送请求,及发送信息
-1:这里就是步骤4中的处理函数的书写了
下面贴出ajax聊天器的代码(无数据库)
聊天器聊天界面代码:
<%@ 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 'chat2.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"> var input; var XMLHttpReq; function createXMLHttpRequest() { input=document.getElementById("123"); input.focus(); XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP"); var chatMsg=input.value; var url = "Chat.do"; XMLHttpReq.open("post", url, true); XMLHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); XMLHttpReq.onreadystatechange = processResponse; //发送请求后,将聊天信息的输入文本框清空 input.value=""; //发送请求,send的参数包含许多的key-value对 //即以“请求参数名=请求参数值”的形式发送请求参数 XMLHttpReq.send("chatMsg=" + chatMsg); // 发送请求 } function sendEmptyRequest() { //创建XMLHttpRequest对象 if(window.XMLHttpRequest) { XMLHttpReq=new XMLHttpRequest(); } if (window.ActiveXObject) { try { //使用AcitveXObject函数创建浏览器 XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { //如果出现异常,再次尝试以如下方式创建XMLHttpRequest对象 try { XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { window.alert("internet"); } } } //定义服务器响应的URL var url = "Chat.do"; //建立与服务器的连接 XMLHttpReq.open("post", url, true); //设置发送请求的参数格式 XMLHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //指定响应处理函数 XMLHttpReq.onreadystatechange = processResponse; //发送请求 XMLHttpReq.send(null); setTimeout("sendEmptyRequest()", 800); } function processResponse() { //如果服务器响应已经完成 if(XMLHttpReq.readyState == 4) { //判断对象状态,如果服务器生成了正常响应 if (XMLHttpReq.status == 200) { //信息已经成功返回,开始处理信息 //将聊天文本域的内容设置成聊天信息 document.getElementById("chatArea").value = XMLHttpReq.responseText; } else { //页面不正常 window.alert("您所请求的页面有异常。"); } } } function enterHandler(event) { //定义键盘中发出事件的键 var keyCode=event.keyCode?event.keyCode:event.which?event.which: event.charCode;//回车键的代码为13,如果按下了回车键 if (keyCode == 13) { createXMLHttpRequest(); } } </script> </head > <body onload="JavaScript:sendEmptyRequest();"> <input type="button" onclick="JavaScript:createXMLHttpRequest();" value="clickme"> <table width="780" border="1" align="center"> <tr> <td><p align="center">聊天页面</p> <!-- 下面定义聊天使用的文本域,该文本域用于显示当前聊天信息 --> <p align="center"> <textarea id="chatArea" name="chatArea" cols="100" rows="30" readonly="readonly"></textarea> </p> <div align="center"> <!-- 下面是输入聊天信息所使用的文本,并为onKeyPress事件指定了监听函数 --> <input id="123" name="chatMsg" type="text" size="90" onKeyPress="JavaScript:enterHandler(event);"> <!-- 下面是输入聊天信息的文本框,并为onclick事件指定了监听函数 --> <input type="button" name="button" value="提交" onclick="JavaScript:createXMLHttpRequest();"> </div> <p> </p> </td> </tr> </table> </body> </html>
有三个控制类处理类(servlet)
1:注册控制处理
package com.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.method.ChatService; public class RegServlet extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name=request.getParameter("username"); String pass=request.getParameter("password"); if(name==null||pass==null) { request.setAttribute("tip", "用户名和密码都不能为空"); forward("/reg.jsp", request, response); } //开始调用业务逻辑对象的方法 try { //调用业务逻辑对象的方法 if (ChatService.instance().addUser(name, pass)) { //如果注册成功,则将提示信息存入系统的tip属性 request.setAttribute("tip", "注册成功,请登录系统"); //将请求转发到reg.jsp页面显示 forward("/reg.jsp", request, response); } else { //如果不能正常注册,则将提示信息放入request属性 request.setAttribute("tip", "无法正常注册,请重试"); forward("/reg.jsp", request, response); } } //如果捕捉到异常,例如注册的用户名已经存在 catch (Exception e) { //将异常信息设置成request属性 request.setAttribute("tip", e.getMessage()); forward("/reg.jsp", request, response); } } private void forward(String url, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext sc = getServletConfig().getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(request, response); } /** * Constructor of the object. */ public RegServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the GET method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
2:登陆控制处理类:
package com.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.method.ChatService; public class LoginServlet extends HttpServlet { /** * Constructor of the object. */ public LoginServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the GET method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name=request.getParameter("username"); String pass=request.getParameter("password"); if(ChatService.instance().validLogin(name, pass)) { request.getSession().setAttribute("username", name); String message=ChatService.instance().getMsg(); request.setAttribute("message", message); forward("/chat2.jsp",request,response); } else { request.setAttribute("tip", "用户名和密码不匹配"); forward("/login.jsp",request,response); } } private void forward(String url, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext sc = getServletConfig().getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(request, response); } }
3:聊天控制处理类:
package com.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.method.ChatService; public class ChatServlet extends HttpServlet { /** * Constructor of the object. */ public ChatServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the GET method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=gbk"); PrintWriter out = response.getWriter(); out .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the GET method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String msg=request.getParameter("chatMsg"); String user=(String) request.getSession().getAttribute("username"); if(msg!=null) { ChatService.instance().addMsg(user, msg); } // String message=ChatService.instance().getMsg(); // request.setAttribute("message", message); // forward("/chat.jsp",request,response); //设置中文输出流 response.setContentType("text/html;charset=utf-8"); //获取页面输出流 PrintWriter out = response.getWriter(); //将当前系统的聊天记录输出到页面 out.println(ChatService.instance().getMsg()); } private void forward(String url, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext sc = getServletConfig().getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(request, response); } }
然后就是web.xml的配置了
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>RegServlet</servlet-name> <servlet-class>com.servlet.RegServlet</servlet-class> </servlet> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>ChatServlet</servlet-name> <servlet-class>com.servlet.ChatServlet</servlet-class> </servlet> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>RegServlet</servlet-name> <url-pattern>/Reg.do</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ChatServlet</servlet-name> <url-pattern>/Chat.do</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/Login.do</url-pattern> </servlet-mapping> </web-app>
最后就是业务处理了:
package com.method; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.LinkedList; import java.util.Properties; public class ChatService { private static ChatService cs; private Properties userList; private LinkedList<String> chatMsg; private ChatService() {} public static ChatService instance() { if(cs==null) { cs=new ChatService(); } return cs; } public boolean validLogin(String user,String pass)throws IOException { if(loadUser().getProperty(user)==null) { return false; } if(loadUser().getProperty(user).equals(pass)) { return true; } return false; } public boolean addUser(String name,String pass)throws Exception { if(userList==null) { userList=loadUser(); } if(userList.containsKey(name)) { throw new Exception("用户名已经存在,请重新选择用户名"); } userList.setProperty(name,pass); saveUserList(); return true; } public String getMsg() { if(chatMsg==null) { chatMsg=new LinkedList<String>(); return ""; } String result=""; for(String tmp:chatMsg) { result+=tmp+"\n"; } return result; } public void addMsg(String user,String msg) { if(chatMsg==null) { chatMsg=new LinkedList<String>(); } if(chatMsg.size()>40) { chatMsg.removeFirst(); } chatMsg.add(user+"说:"+msg); } private Properties loadUser()throws IOException { if(userList==null) { File f=new File("userFile.properties"); if(!f.exists()) f.createNewFile(); userList=new Properties(); userList.load(new FileInputStream(f)); } return userList; } private boolean saveUserList()throws IOException { if(userList==null) { return false; } userList.store(new FileOutputStream("userFile.properties"), "userList"); return true; } }
至此ajax聊天器的程序测试就这样完成了。
相关推荐
基于java的开发源码-Ajax框架 ZK.zip 基于java的开发源码-Ajax框架 ZK.zip 基于java的开发源码-Ajax框架 ZK.zip 基于java的开发源码-Ajax框架 ZK.zip 基于java的开发源码-Ajax框架 ZK.zip 基于java的开发源码-Ajax...
基于java的开发源码-ajax写的登录实例.zip 基于java的开发源码-ajax写的登录实例.zip 基于java的开发源码-ajax写的登录实例.zip 基于java的开发源码-ajax写的登录实例.zip 基于java的开发源码-ajax写的登录实例.zip ...
学习ajax之----掌握Ajax,学习ajax之----掌握Ajax ,学习ajax之----掌握Ajax ,学习ajax之----掌握Ajax
Ajax-magento2-catalog-infinite-scroll.zip,免费的Magento 2扩展,为目录添加无限滚动功能(通过AJAX实现)编码教程,ajax代表异步javascript和xml。它是多种web技术的集合,包括html、css、json、xml和javascript。...
传智播客培训 - AJAX技术入门 - 王兴魁 老师
学习-学习平台-学习平台源码-学习平台java代码-学习平台设计与实现-基于springboot的学习平台-基于Web的学习平台设计与实现-学习网站-学习网站源码-学习网站java代码-学习项目-学习项目代码-学习系统-学习系统源码-...
Ajax分页组件--web-java,美观通用
积分多的大佬打赏下,缺积分用;积分不够得移步https://www.cnblogs.com/BambooLamp/p/12603299.html 原文:https://segmentfault.com/a/1190000012469713
ajax课件--------Ajax.ppt,绝对经典,放心下载!
Ajax-Online-java-compiler.zip,在线Java编译器,ajax代表异步javascript和xml。它是多种web技术的集合,包括html、css、json、xml和javascript。它用于创建动态网页,其中网页的小部分在不重新加载网页的情况下更改...
书籍学习-书籍学习平台-书籍学习平台源码-书籍学习平台java代码-书籍学习平台设计与实现-基于springboot的书籍学习平台-基于Web的书籍学习平台设计与实现-书籍学习网站-书籍学习网站源码-书籍学习网站java代码-书籍...
Ajax-magento2-ajax-layered-navigation.zip,ajax分层导航magento 2提供了一个过滤器列表,帮助您的客户以最短的方式搜索和获得他们最喜欢的产品。这个扩展应用了现代ajax技术来增强过滤系统,以提高用户对页面上每...
Ajax-magento2-ajax-cart-quick.zip,magento 2 ajax购物车扩展插件提供舒适的购物体验。客户可以很容易地选择可配置的选项并在弹出窗口中编辑项目,而不会浪费重新加载页面的时间。,ajax代表异步javascript和xml。它...
详细介绍了Ajax技术 简单的实例 让你快速精通Ajax技术
Ajax与Java高级程序设计
AJAX技术入门--详细介绍Ajax的机理和实现技术,包括Javascript语言、Xml、XMLHttpRequest对象等的介绍~~~
Ajax与Java高级程序设计
Ajax与Java高级程序设计
NULL 博文链接:https://lc2586.iteye.com/blog/725751