**

*中文问题,有兴趣可以解决一下

**

*************/

 

 

/***

*index.jsp

****/

<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">
   function checkName()
   {
      var userName=document.getElementById("username").value;
      if(userName==null||userName=="")
      {
        
      }
   }
  function doSubmit(){
   window.location.href
  }
 </script>
 </head>
 <table width="600" height="200" border="1" align="center"
  cellpadding="0" cellspacing="0">
  <tr>
   <td align="center">
    <form name="form1" method="post"
     action="LoginServlet">
     您的昵称:
     <input name="username" type="text" id="username"><br>
     <input type="submit" name="Submit" value="进入">
    </form>
   </td>
  </tr>
 </table>
 <body>
  <
 </body>
</html>

/****

**main.jsp

*****/

<%@ page language="java" pageEncoding="gbk"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title></title>
<script type="text/javascript">
var HttpRequest;//定义变量用于存储xmlHttpReques
var url = "MessageServlet";//定义变量存储请求地址
function getRequest(){//创建xmlHttpRequest对象
   if(window.ActiveXObject){//如果是IE浏览器
   return new ActiveXObject("Microsoft.XMLHTTP");
  
  }else if(window.XMLHttprequest){//非IE浏览器
   return new XMLHttpRequest();
  
  }
}
function sendRequest(){
    if(document.getElementById("txtMessage").value.length<=0){//判断消息是否为空
        return false;
    }
    HttpRequest = getRequest();//回调
   
    //HttpRequest.onreadystatechange = getMessage;
    HttpRequest.open("POST", url, true);//初始化xmlHttprequest组件
    HttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    var msg;
    msg = "Action=AddMessage&Message=" + escape(document.getElementById("txtMessage").value);
    //发送请求
    HttpRequest.send(msg);
    //清空文本
    document.getElementById("txtMessage").value = "";
    //document.getElementById("txtMessage").focus();
}
function DisplayMessage(){
//判断是否成功
    if(HttpRequest.readyState == 4 && HttpRequest.status == 200){
        //alert("1111111111111111111111111");
        //alert(HttpRequest.responseText);
        var messages;
        //alert(HttpRequest.responseText);
        messages = HttpRequest.responseText.split("!@#");
        //document.writeln(messages[0]);
        //document.writeln(messages[1]);
        //把值放进去
        document.getElementById("Messages").innerHTML = messages[0];
        document.getElementById("userList").innerHTML = "用户列表 <br>" + messages[1];
       
    }
}
function logout(){//退出浏览器()
    HttpRequest = getRequest();//获得xmlHttpRequest对象
    HttpRequest.open("POST", url, true);
    HttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    var msg;
   
    msg = "Action=Logout";
    HttpRequest.send(msg);
}
function getMessage(){
    //获得xmlHttpRequest对象
    HttpRequest = getRequest();
    //设置回调函数
    HttpRequest.onreadystatechange = DisplayMessage;
    //初始化xmlHttpRequest组件
    HttpRequest.open("POST", url, true);
    HttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    //请求串
    var msg;
    msg = "Action=GetMessage";
    //发送请求
    HttpRequest.send(msg);
    document.all.txtMessage.focus();
}
function login(){
    HttpRequest = getRequest();//获得xmlHttpRequest对象
    var WshNetwork = new ActiveXObject("Microsoft.XMLHTTP");
    //初始化xmlHttpRequest组件
    HttpRequest.open("POST", url, true);
    //请求标头
    HttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    var msg;
    msg = "Action=Login&UserName=" + WshNetwork.UserName;
    HttpRequest.send(msg);  //发送请求
   
    setInterval('getMessage();', 1000);//1秒调用
}

</script>
</head>
<body οnunlοad="logout();" οnlοad="login();">
    <form action="#" οnsubmit="return false;">
    <table>
        <tr valign="top">
            <td width="400"><div id="Messages" style="font-size:9pt;width:800;height:400"></div></td>
            <td width="100" id="userList"></td>
        </tr>
    </table>
    <input type="text" size="20" id="txtMessage">
    <button οnclick="sendRequest();">发言</button>
    </form>
</body>
</html>

 /******

**LoginServlet登陆servlet*

*/

package com.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {
 static final long serialVersionUID = 1L;
 

 /**//*
   * (non-Java-doc)
   *
   * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
   *      HttpServletResponse response)
   */
 @SuppressWarnings("unchecked")
 protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {

  //中文乱码
  response.setContentType("text/html;charset=gbk");
  // // response.setCharacterEncoding("gbk");
  request.setCharacterEncoding("gbk");
  String name = request.getParameter("username");
  ServletContext context = getServletContext();
  //取出用户并判断是否为空
  List onlineUsers = (List) context.getAttribute("UserList");
  if (onlineUsers == null) {
   onlineUsers = new ArrayList();
  }
  onlineUsers.add(name + "<br>");
//把用户放到session和context
  request.getSession().setAttribute("UserName", name);
  context.setAttribute("UserList", onlineUsers);
  response.sendRedirect("main.jsp");

  // TODO Auto-generated method stub
 }

 /**//*
   * (non-Java-doc)
   *
   * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest
   *      request, HttpServletResponse response)
   */
 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  doGet(request, response);
  // TODO Auto-generated method stub
 }

 public void destroy() {
  super.destroy();
 }

}
/**

**MessageServlet.java

********/

package com.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MessageServlet extends HttpServlet {

 /**
  *
  */
 private static final long serialVersionUID = 6094443235725623307L;

 /**
  * 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
  */
 private String userName = "";

 /**//*
   * (non-Java-doc)
   *
   * @see javax.servlet.http.HttpServlet#HttpServlet()
   */
 public MessageServlet() {
  super();
 }

 // 获取当前时间
 private String getNow() {
  Date date = new Date();
  // 转换时间格式
  SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
  return df.format(date);
 }

 /**//*
   * (non-Java-doc)
   *
   * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
   *      HttpServletResponse response)
   */
 @SuppressWarnings("unchecked")
 protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
//  中文乱码
  response.setContentType("text/html;charset=gbk");
  // // response.setCharacterEncoding("gbk");
  request.setCharacterEncoding("gbk");
  String action = request.getParameter("Action");// 获取Actio判断请求参数
  if (action == null) {
  } else if (action.equals("GetMessage")) {
   PrintWriter out = response.getWriter();
   // System.out
   // .println("333" + getMessages() + "!@#" + getOnlineUsers());
   // 获取信息和用户输出
   out.print(getMessages() + "!@#" + getOnlineUsers());
  } else if (action.equals("AddMessage")) {
   response.setContentType("gbk");
   // 获取请求消息
   String message = request.getParameter("Message");
   userName = (String) request.getSession().getAttribute("UserName");
   // 调用addMessage()方法追加消息
   addMessage(getNow() + " " + userName + " Says: " + message);
  } else if (action.equals("Logout")) {//关闭浏览器清除用户(不知道问什么不管用)
   ServletContext context=getServletContext();
   List userList = (List)context .getAttribute("UserList");
   userList.remove("UserName");
   context.removeAttribute("UserList");
   context.setAttribute("UserList", userList);

  } else if (action.equals("Login")) {
   String name = (String) request.getSession()
     .getAttribute("UserName");
   request.getSession().setAttribute("UserName", name);
  }
  // TODO Auto-generated method stub
 }

 /**//*
   * (non-Java-doc)
   *
   * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest
   *      request, HttpServletResponse response)
   */
 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  doGet(request, response);
  // TODO Auto-generated method stub
 }

 @SuppressWarnings("unchecked")
 private String getMessages() {
  String result = null;
  ServletContext application = getServletContext();
  List messages = (List) application.getAttribute("ChatMessage");
  if (messages == null) {
   result = "";
  } else {
   StringBuilder sb = new StringBuilder();
   for (int i = 0; i < messages.size(); i++) {
    sb.append(messages.get(i));
    sb.append("<br>");
   }
   result = sb.toString();
   System.out.println("11111111111" + sb.toString());
  }
  return result;
 }

 @SuppressWarnings("unchecked")
 private String getOnlineUsers() {
  String result;
  List onlineUsers = (List) getServletContext()
    .getAttribute("UserList");
  if (onlineUsers == null) {
   result = "";
  } else {
   StringBuffer users = new StringBuffer();// new
   // 一个StringBuffer存放用户
   for (int i = 0; i < onlineUsers.size(); i++) {
    users.append(onlineUsers.get(i));
    users.append("<br>");
   }
   result = users.toString();
   System.out.println("2222222222" + result);
  }
  return result;
 }

 @SuppressWarnings("unchecked")
 private void addMessage(String message) {
  ServletContext application = getServletContext();

  //获取消息
  List messages = (List) application.getAttribute("ChatMessage");
  if (messages == null) {//为空new对象
   messages =new ArrayList();
  }
  if (messages.size() > 2) {//大于15删除第一个
   messages.remove(0);
  }
  messages.add(message);
  application.setAttribute("ChatMessage", messages);
 }

 public void destroy() {
  super.destroy();
 }

}
/***

*SetCharacterEncodingFilter.java

*******/

package com.servlets;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class SetCharacterEncodingFilter implements Filter {
   protected FilterConfig filterConfig;
   protected String encodingName;
   protected boolean enable;
   public SetCharacterEncodingFilter() {
     this.encodingName = "GBK";
     this.enable = false;
   }

   public void init(FilterConfig filterConfig) throws ServletException {
     this.filterConfig = filterConfig;
   }

   public void doFilter(ServletRequest request,
                        ServletResponse response,
                        FilterChain chain)
                     throws IOException, ServletException {
     request.setCharacterEncoding("GBK");
     response.setCharacterEncoding("GBK");
     response.setContentType("text/html;charset=gbk");
     chain.doFilter(request, response);
   }

   public void destroy() {
   }