ajaxとjavaを組み合わせた学習(入門--ajaxチャット)まとめ
思想闘争は长くて、ついにajaxに接触し始めて、初心者として、真似するのは悪くない学习方法で、少なくとも私はこのように学んで来て、巨人の肩の上に立っています.
今回のパロディーの内容は『J 2 EEに基づくAjax宝典』電子書籍から来ており、ここで感謝の意を表します.紹介するのはJspページチャットとajaxチャットの前の器の違い、およびajaxの特徴の体現です.
---従来のJSPチャットルームに比べて、Ajaxチャットルームの速度が速く、応答がスムーズです.複雑なページの場合、Ajaxの利点はさらに明らかになります.Ajaxチャットルームは、ページ全体をダウンロードすることなく、サーバから更新する必要があるチャットレコードを取得するだけです.
Ajaxチャットルームの最大の特徴は、ページを更新する必要がなく、ユーザーがページのダウンロードを感じないことです.Ajaxチャットルームを使用すると、ユーザーは普通のSocketチャットルームを使用しているように感じます.チャットルームのページはリフレッシュする必要はありませんが、ユーザーのチャット情報はリアルタイムで更新されます.これらはすべてAjaxの非同期送信要求と動的更新ページに依存します.
学習能力が強いと自称する私は、これでやっとどんなにちっぽけなことかを知って、丸1日かけてやっと実現することができて、しかしこの過程は負けて光栄ですが、ajax機能の実現の全体の流れをもっと深く理解しました.
1:XMLHttpRequestオブジェクトの作成
2:サーバとの接続を取得する(postリクエスト用)
3:postリクエストの送信時にファイルヘッダを追加する必要があります
4:XMLHttpRequestステータスが変化した場合の処理関数を指定します(リスニングプロセス).
5:リクエストの送信、およびメッセージの送信
-1:ここで手順4の処理関数の書き方です
次にajaxチャットのコードを貼り付けます(データベースなし)
チャットチャットのインタフェースコード:
3つの制御クラス処理クラス(servlet)があります
1:登録制御処理
2:登録制御処理類:
3:チャット制御処理類:
そしてwebです.xmlの構成
最後にビジネス処理です.
これでajaxチャットのプログラムテストが完了しました.
今回のパロディーの内容は『J 2 EEに基づくAjax宝典』電子書籍から来ており、ここで感謝の意を表します.紹介するのはJspページチャットとajaxチャットの前の器の違い、およびajaxの特徴の体現です.
---従来のJSPチャットルームに比べて、Ajaxチャットルームの速度が速く、応答がスムーズです.複雑なページの場合、Ajaxの利点はさらに明らかになります.Ajaxチャットルームは、ページ全体をダウンロードすることなく、サーバから更新する必要があるチャットレコードを取得するだけです.
Ajaxチャットルームの最大の特徴は、ページを更新する必要がなく、ユーザーがページのダウンロードを感じないことです.Ajaxチャットルームを使用すると、ユーザーは普通のSocketチャットルームを使用しているように感じます.チャットルームのページはリフレッシュする必要はありませんが、ユーザーのチャット情報はリアルタイムで更新されます.これらはすべてAjaxの非同期送信要求と動的更新ページに依存します.
学習能力が強いと自称する私は、これでやっとどんなにちっぽけなことかを知って、丸1日かけてやっと実現することができて、しかしこの過程は負けて光栄ですが、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>
3つの制御クラス処理クラス(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+"
";
}
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チャットのプログラムテストが完了しました.