jsp如何实现简单的在线聊天功能

2025-01-24 03:39:07
推荐回答(3个)
回答1:

先做一个用户交流界面 参考代码 你可以参考里面的关键代码request.getContextPath();
















再做一个程序来处理客户的交流信息可以参考dopost()方法里的代码
package server;

import java.io.IOException;
import java.io.PrintWriter;

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;

public class serverMyJsp extends HttpServlet {

public serverMyJsp() {
super();
}

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

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
response.setContentType("text/html");
PrintWriter out = response.getWriter();

}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
response.setCharacterEncoding("gbk");
request.setCharacterEncoding("gbk");
//String demo=request.getParameter("message");
// String str=new String(demo.getBytes("Iso-885-1"),"gbk()");
ServletContext sc=this.getServletContext();
String uname=(String) request.getSession().getAttribute("aa");
System.out.println(uname);
String amessage=(String) sc.getAttribute("message");
sc.setAttribute("message", amessage+uname+"说:"+request.getParameter("message")+"\r\n");
response.sendRedirect("../MyJsp.jsp");

}

public void init() throws ServletException {
}

}

回答2:

用AJAX比较好,其实直接用AJAX底层XmlHttpRequest实现最好
也不难,纯JAVASCRIPT就搞掂
聊天如果不断刷新那就真是。。

回答3:

用session和application能实现