基于Java语言的Web在线聊天室

article/2025/10/14 0:26:48

在线聊天室

能够实现登录,注册,聊天功能,最终效果如下图所示
最终效果

注册页面

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="Register" name="form1" method="post">输入账号:<input name="account" type="text"><BR> 输入密码:<inputname="password" type="password"><BR> 输入真实姓名:<inputname="realname" type="text"><br/><input type="submit"value="注册并登录"><br/></form>
</body>
</html>

注册失败页面

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
注册失败
</body>
</html>

登录界面

<%@page import="java.util.ArrayList" %><%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %><!DOCTYPE html><html><head><meta charset="utf-8"><title>Insert title here</title><style>.mainlogin {width: 500px;height: 500px;margin: 0px auto;}.logindiv {margin-top: 100px;}</style></head><body><% /*初始化application*/ ArrayList customers=(ArrayList) application.getAttribute("customers"); if(customers==null) { customers=new ArrayList(); application.setAttribute("customers", customers); }ArrayList msgs=(ArrayList) application.getAttribute("msgs"); if (msgs==null) { msgs=new ArrayList();application.setAttribute("msgs", msgs); } %><div class="mainlogin"><div class="logindiv"><div style="width: 100%; text-align: center;">欢迎登录聊天系统</div><div style="width: 100%; text-align: center;"><form action="loginAction" name="form1" method="post">输入账号:<input name="account" type="text"><BR> 输入密码:<input name="password" type="password"><br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<inputtype="submit" style="width: 150px;" value="登录"><br /><span>还没有账号?</span><a href="register.jsp">注册</a></form></div></div></div></body></html>

聊天界面

<%@page import="renaofeiChatRoom.bean.Customer"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>欢迎进入聊天室</title>
</head>
<body><%Customer customer = (Customer)session.getAttribute("customer");%><span>欢迎&nbsp;<span style="color:red" ><%=customer.getCname() %></span>&nbsp;进入聊天室</span><HR><form action="chatAction" name="form1" method="post">输入聊天信息:<input name="msg" type="text" size="40"> <inputtype="submit" style="width: 100px;" value="发送"></form><br><br><a href="logout">退出登录</a><HR><iframe src="msgs.jsp" width="100%" height="100%" style="height: 500px;" frameborder="0"></iframe>
</body>
</html>

消息界面,因为需要异步刷新,采用iframe标签进行刷新

<%@page import="renaofeiChatRoom.bean.Customer" %><%@page import="java.util.ArrayList" %><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %><!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title></head><body><% response.setHeader("Refresh","5"); %><table width="80%" border="0" align="center"><tr bgcolor="orange" align="center"><td width="75%">消息</td><td width="25%">当前在线</td></tr><tr bgcolor='pink'><td><% ArrayList msgs=(ArrayList)application.getAttribute("msgs"); for(inti=msgs.size()-1;i>=0;i--){out.println(msgs.get(i) + "<br>");}%></td><td valign='top' style="text-align: center;"><% ArrayList customers=(ArrayList)application.getAttribute("customers"); for(inti=customers.size()-1;i>=0;i--){Customer customer = (Customer)customers.get(i);out.println(customer.getAccount() + "(" + customer.getCname() + ")"+"<br>");}%></td></tr></table></body></html>

OK,前端完毕,下面开始编写后端,这个项目是jsp的,用的原生Servlet进行转发请求,首先,需要连接数据库的代码


public class CustomerDao {private Connection conn = null;public void initConnection() throws Exception {Class.forName("com.mysql.jdbc.Driver");conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/chatdb", "root", "");//数据库连接配置}public Customer getCustomerByAccount(String account) throws Exception {Customer cus = null;initConnection();String sql = "SELECT ACCOUNT,PASSWORD,CNAME FROM T_CUSTOMER WHERE ACCOUNT=?";PreparedStatement ps = conn.prepareStatement(sql);ps.setString(1, account);ResultSet rs = ps.executeQuery();if(rs.next()){cus = new Customer();cus.setAccount(rs.getString("ACCOUNT"));cus.setPassword(rs.getString("PASSWORD"));cus.setCname(rs.getString("CNAME"));}closeConnection();return cus;		}public boolean regeditNewCustomer(String name,String pwd,String rname) throws Exception {Customer cus = null;initConnection();String sql = "INSERT INTO `t_customer` (`ACCOUNT`, `PASSWORD`, `CNAME`) VALUES (?, ?, ?)";PreparedStatement ps = conn.prepareStatement(sql);ps.setString(1, name);ps.setString(2, pwd);ps.setString(3, rname);int flag=0;try {flag = ps.executeUpdate();closeConnection();} catch (Exception e) {closeConnection();}return flag>=1;}public void closeConnection() throws Exception {conn.close();}
}

然后需要一个用户的类,用来存储信息

public class Customer {private String account;private String password;private String cname;public String getAccount() {return account;}public void setAccount(String account) {this.account = account;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getCname() {return cname;}public void setCname(String cname) {this.cname = cname;}
}

然后就是4个servlet转发请求,注册的请求如下


/*** Servlet implementation class Register*/
@WebServlet("/Register")
public class Register extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public Register() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub//response.getWriter().append("Served at: ").append(request.getContextPath());ServletContext application=this.getServletContext();HttpSession session=request.getSession();request.setCharacterEncoding("UTF-8");String account = request.getParameter("account");String password = request.getParameter("password");String realname = request.getParameter("realname");CustomerDao cdao = new CustomerDao();boolean flag=false;try {flag=cdao.regeditNewCustomer(account, password, realname);} catch (Exception e) {}if(flag) {Customer customer=null;try {customer = cdao.getCustomerByAccount(account);} catch (Exception e) {// TODO: handle exception}if (customer == null || !customer.getPassword().equals(password)) {response.sendRedirect("loginForm.jsp");} else {session.setAttribute("customer", customer);ArrayList customers = (ArrayList) application.getAttribute("customers");if (customers == null) {customers = new ArrayList();application.setAttribute("customers", customers);}ArrayList msgs = (ArrayList) application.getAttribute("msgs");if (msgs == null) {msgs = new ArrayList();application.setAttribute("msgs", msgs);}customers.add(customer);msgs.add(customer.getCname() + "上线啦!");response.sendRedirect("chatForm.jsp");}}else {response.sendRedirect("regFailed.jsp");}}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}

登录的请求如下


/*** Servlet implementation class loginAction*/
@WebServlet("/loginAction")
public class loginAction extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public loginAction() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse*      response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// TODO Auto-generated method stub// response.getWriter().append("Served at: ").append(request.getContextPath());//��¼����ServletContext application=this.getServletContext();HttpSession session=request.getSession();request.setCharacterEncoding("UTF-8");String account = request.getParameter("account");String password = request.getParameter("password");//out.println(account);CustomerDao cdao = new CustomerDao();Customer customer=null;try {customer = cdao.getCustomerByAccount(account);} catch (Exception e) {// TODO: handle exception}if (customer == null || !customer.getPassword().equals(password)) {response.sendRedirect("loginForm.jsp");} else {session.setAttribute("customer", customer);ArrayList customers = (ArrayList) application.getAttribute("customers");if (customers == null) {customers = new ArrayList();application.setAttribute("customers", customers);}ArrayList msgs = (ArrayList) application.getAttribute("msgs");if (msgs == null) {msgs = new ArrayList();application.setAttribute("msgs", msgs);}customers.add(customer);msgs.add(customer.getCname() + "上线啦!");response.sendRedirect("chatForm.jsp");}}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse*      response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}

发消息的请求如下


/*** Servlet implementation class chatAction*/
@WebServlet("/chatAction")
public class chatAction extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public chatAction() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse*      response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// TODO Auto-generated method stub// response.getWriter().append("Served at: ").append(request.getContextPath());ServletContext application = this.getServletContext();HttpSession session = request.getSession();Customer customer = (Customer) session.getAttribute("customer");request.setCharacterEncoding("utf-8");String msg = request.getParameter("msg");ArrayList<String> msgs = (ArrayList) application.getAttribute("msgs");if (msgs == null) msgs = new ArrayList();msgs.add(customer.getCname() + "说:" + msg);response.sendRedirect("chatForm.jsp");}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse*      response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}

退出登录的消息如下


/*** Servlet implementation class logout*/
@WebServlet("/logout")
public class logout extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public logout() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub//response.getWriter().append("Served at: ").append(request.getContextPath());ServletContext application=this.getServletContext();HttpSession session=request.getSession();Customer customer = (Customer)session.getAttribute("customer");// session.getAttribute("customer");ArrayList customers = (ArrayList) application.getAttribute("customers"); customers.remove(customer);ArrayList msgs = (ArrayList)application.getAttribute("msgs");msgs.add(customer.getCname() + "下线啦!");  session.invalidate();response.sendRedirect("loginForm.jsp");}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}

上面这些这就是全部代码了,资源地址如下
基于Java的在线的聊天室


http://chatgpt.dhexx.cn/article/tlCylfJh.shtml

相关文章

Springboot+netty实现Web聊天室

Web聊天室的实现 一、项目的创建二、代码编写参考 一、项目的创建 新建Spring项目&#xff1a; 选择JDK版本&#xff1a; 选择Spring Web&#xff1a; 项目名称和位置的设置&#xff1a; 二、代码编写 导入.jar包&#xff1a; gson: https://search.maven.org/artifact/co…

用springboot+netty搭建在线web聊天室

最近自己搭建了一个在线的聊天室&#xff0c;利用netty技术开发&#xff0c;实现在线聊天以及群聊功能&#xff0c;包括好友添加等相关功能&#xff0c;目前还在更新中。 1.我是通过springbootnetty实现&#xff0c;通过使用netty4实现&#xff0c;运用这种方式就可以帮助我们…

基于SSM的Web网页聊天室系统

目 录 第1章 前 言 1 1.1 论文研究的目的和意义 1 1.2 国内外研究综述 2 1.3 论文研究的内容和取得的成果 2 第2章 即时通讯聊天系统开发涉及技术简介 4 2.1 Spring简介 4 2.2 SpringMVC简介 4 2.3 MyBatis简介 5 2.4 AmazeUI简介 5 2.5 开发工具介绍 5 2.5.1 Eclipse集成开发环…

【项目设计】基于WebSocket的Web聊天室

文章目录 1. 项目简介2. 数据库表的设计3. 实体类以及工具类的设计3.1 实体类model3.1.1 lombok的使用 3.2 工具类util3.2.1 DBUtil3.2.2 WebUtil 4. 注册功能4.1 前端设计4.2 关于Ajax技术的介绍4.3 后端设计 5. 登陆功能5.1 前端设计5.2 后端设计 6. 获取频道列表6.1 前端设计…

手把手教你写一个web聊天室之bookstap框架

一&#xff1a;bookstap简介 Bootstrap&#xff0c;来自 Twitter&#xff0c;是目前最受欢迎的前端框架。Bootstrap 是基于 HTML、CSS、JAVASCRIPT 的&#xff0c;它简洁灵活&#xff0c;使得 Web 开发更加快捷。并且对开发响应式网页十分友好&#xff0c;使用框架进行网页开发…

从零开始搭建 web 聊天室(一)

本篇将介绍如何快速、简便地使用 socket.io 库搭建一个 web 在线聊天室。前端并没有使用任何框架。后端使用 express 框架搭建简易的后端。 socket.io 库本质上是基于 websocket 上进行封装。改变了以往只能前端发送请求&#xff0c;后端才能返回给前端信息&#xff0c;这样的…

基于socket.io的web聊天室

基于socket.io的web聊天室 一、 项目介绍 该项目使用node.js作为后端服务器框架&#xff0c;并利用socket.io来实现web聊天室功能。socket.io是由 JavaScript 实现的基于Node.js架构体系的用于实时通信的开源框架&#xff0c;它包括了客户端的 JavaScript 库和 服务器端的 No…

一个轻量级多功能免费开源web聊天室

一个轻量级多功能免费开源web聊天室&#xff0c;轻量级实用功能多而强悍的聊天室系统 版本特点&#xff1a; 支持图文发送,兼容QQ内置,微信内置,pc等浏览器 无需服务端操作,phpmysql高效运行,无需第三方插件 高效极快的运行速度 聊天室bbs推送 多功能聊天室 支持一键粘贴网页图…

web聊天室项目开发过程及重难点整理

目录 一、需求分析二、业务背景1.张三要发消息给李四2.WebSocket实现消息推送流程 三、前后端接口和数据库系统设计1.用户相关的接口2.频道相关接口3.数据库表的设计 四、功能交互实现原理及代码展示1.输入url访问主页2.调用检查登陆状态接口2.1参数ok&#xff1a;true时显示登…

django WEB聊天室项目

bbs系统项目中我们用到的ajax不多,但是在聊天室里用到的全是ajax,所以本项目的主要内容就是: 前端使用ajax传输json格式的数据是本节的重点以及 前端函数的的使用. http协议的特点是:短链接 ,服务器无法主动向客户端发送消息.都是客户端请求服务器返回消息. 那么问题来了,WEB聊…

Web聊天室项目

Web聊天室 项目描述所用技术业务分析接口设计和整体业务流程相关代码程序演示 项目描述 实现一个类似于在线QQ聊天的功能&#xff0c;不同的用户可以在相同的频道里发送和接受消息从而达到在线聊天的功能。 项目的主要功能有&#xff1a;注册用户、用户登陆、频道主页、进入频…

Web聊天室

目录 一&#xff0c;简介 二&#xff0c;开发环境 三&#xff0c;涉及的技术 四&#xff0c;主要功能 1.注册功能 2.登录功能 3.异地登陆&#xff08;第一次登录网页会被强制退出&#xff09; 4.发送消息 5.接收消息 6.注销登录 五&#xff0c;准备工作 1.引入开发…

八个步骤实现一个Web项目(在线聊天室)

实现一个在线网页的聊天室 Hello&#xff0c;今天给大家带来的是我的一个Web项目的开发过程的相关步骤&#xff0c;这个项目实现的功能是一个Web在线聊天室&#xff0c;简单的来说就是实现在网页版的聊天框&#xff0c;能够实现对于用户信息进行注册&#xff0c;登录&#xff…

基于JavaWeb聊天室设计与实现

目 录 摘要 i Abstract ii 1 概述 1 1.1 聊天室系统的基本概念 1 1.2 开发聊天室系统的意义 1 1.3 目前的研究现状 1 1.4 总体设计的基本思路 1 2 主要技术 3 2.1 JSP技术 3 2.2 JavaBean技术 4 2.3 Servlet技术 4 2.4 MyEclipse开发工具 6 2.5 Access数据库技术 6 2.6 Tomcat…

【Hadoop篇】启动hdfs集群时,提示: ERROR: Cannot set priority of zkfc process 5668

【问题描述】 启动hdfs集群时&#xff0c;遇到如下错误 [dylanhadoop102 hadoop]$ start-dfs.sh Starting namenodes on [hadoop102] Starting datanodes Starting secondary namenodes [hadoop104] Starting ZK Failover Controllers on NN hosts [hadoop102] hadoop102: ERR…

hadoop(XShell) 出现错误ERROR: Cannot set priority of namenode process 7927

项目场景&#xff1a; 网页上出错&#xff1a;&#xff08;出现这种问题有时候也可能是没有关闭防火墙&#xff09;&#xff0c;也可能是一下这种错误。 XShell上出错&#xff1a; 问题描述 XShell提示该地方出错&#xff1a; 上面说了是mapred-site.sml文件出错了 原因分析…

Yarn启动报错,ERROR: Cannot set priority of registrydns process xxxxx

问题&#xff1a; HDP 安装 yarn 时。或者重启服务的时候&#xff0c;yarn registry dns 无法启动。如下图所示&#xff1a; 报错信息&#xff1a; 查看报错信息&#xff0c;报错信息如下所示&#xff1a; ERROR: Cannot set priority of registrydns process xxxxx解决方式…

启动Hadoop集群,出现Cannot set priority of nodemanager(resourcemanager) process xxx问题

背景 &#xff08;不感兴趣可以跳过背景介绍&#xff09; 配置 Ubantu20.04jdk1.8.0_221hadoop 3.3.1hive 3.1.3三台虚拟机搭建Hadoop集群在安装hive的过程中&#xff0c;初始化数据库成功后&#xff08;mysql&#xff09;&#xff0c;输入 命令: ./bin/hive启动hive时出错&a…

【Hadoop】关于Hadoop集群HDFS启动问题:DataNode启动报错ERROR: Cannot set priority of namenode process

关于Hadoop集群HDFS启动问题&#xff1a;NameNode启动正常&#xff0c;DataNode启动报错ERROR: Cannot set priority of namenode process 19826 出了问题第一步一定要先看日志&#xff01;看日志&#xff01;看日志&#xff01; DataNode日志文件在Hadoop目录下的logs文件夹 …

Hadoop安装错误:Cannot set priority of secondarynamenode process : xxxxx

这是由于当前用户与可操作用户不匹配&#xff0c;产生权限冲突 使用以下命令可解决 chown -R root:root 文件名/&#xff0c;如 chown -R root:root hadoop3.1.3/ 成果&#xff1a;