在线聊天室

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

注册页面

<%@ 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的在线的聊天室

基于Java语言的Web在线聊天室相关推荐

  1. 【java毕业设计】基于java+原生Sevlet+socket的聊天室系统设计与实现(毕业论文+程序源码)——聊天室系统

    基于java+原生Sevlet+socket的聊天室系统设计与实现(毕业论文+程序源码) 大家好,今天给大家介绍基于java+原生Sevlet+socket的聊天室系统设计与实现,文章末尾附有本毕业设 ...

  2. 在线聊天JAVA后端_java web 在线聊天的基本实现

    随着互联网的发展,http的协议有些时候不能满足需求,比如在现聊天的实现.如果使用http协议必须轮训,或者使用长链接.必须要一个request,这样后台才能发送信息到前端. 后台不能主动找客户端通信 ...

  3. java毕业设计——基于java+TCP+UDP的局域网聊天室系统设计与实现(毕业论文+程序源码)——局域网聊天室系统

    基于java+TCP+UDP的局域网聊天室系统设计与实现(毕业论文+程序源码) 大家好,今天给大家介绍基于java+TCP+UDP的局域网聊天室系统设计与实现,文章末尾附有本毕业设计的论文和源码下载地 ...

  4. 【云原生之Docker实战】使用Docker部署Web在线聊天室Rocket.Chat

    [云原生之Docker实战]使用Docker部署Web在线聊天室Rocket.Chat 一.Rocket.Chat介绍 二.检查本地系统环境 1.检查系统版本 2.检查docker版本 3.检查doc ...

  5. 基于Server-Sent Event的简单在线聊天室

    一.Web即时通信 所谓Web即时通信,就是说我们可以通过一种机制在网页上立即通知用户一件事情的发生,是不需要用户刷新网页的.Web即时通信的用途有很多,比如实时聊天,即时推送等.如当我们在登陆浏览 ...

  6. Web在线聊天室(2) --- 技术实现原理

    技术实现原理 实现技术原理 (一)Session (二)Ajax 技术 (三)消息推送 轮询方式 长轮询 长连接 webSocket 此项目中的webSocket 实现技术原理 (一)Session ...

  7. Web在线聊天室(6) --- login登录接口

    目录 登录接口 接口设计文档 编写前端ajax回调函数 编写servlet实现dopost方法 编写操作数据库方法 实现结果 检测登录接口 接口设计文档 编写前端ajax回调函数 编写servlet实 ...

  8. WebSocket创建局域网在线聊天室

    WebSocket的简要介绍: WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议. WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服 ...

  9. Java网络编程,使用Java实现UDP和TCP网络通信协议,以及基于UDP的在线聊天室。

    文章目录 前言 一.网络编程概念 1.网络 2. 网络编程的目的 3.想要达到这个效果需要什么 4.网络分层 二.网络编程Java类 1.IP地址:InetAddress 2.端口 3.TCP连接 3 ...

最新文章

  1. Effective C++ 之 Item 6 : 若不想使用编译器自动生成的函数,就该明确拒绝
  2. AlertDialog显示错误 Unable to add window token null is not for an application
  3. 水池数目---深搜思想
  4. Spring Boot中的一些常用配置介绍!
  5. 优秀第三方库-图片浏览
  6. Foundation 框架 NSArray、NSMutableArray排序
  7. 从零基础入门Tensorflow2.0 ----四、15.tf.data读取csv文件并与tf.keras结合使用
  8. cn域名注册国外_国内注册域名有什么规则?有什么要求?
  9. 站长网管工具有哪些用处?
  10. (pythonQQ群管理)通过selenium 自动批量删除QQ群成员
  11. JavaScript打开APP
  12. Squid运行控制脚本_wuli大世界_新浪博客
  13. linux 安装云锁
  14. 【BZOJ1135】【POI2009】Lyz
  15. 【jupyter】2、jupyter主题设置
  16. 怎么在LinkedIn领英安全添加到3万个好友?
  17. 水塔流量的估计matlab,估计水塔的水流量
  18. 去雾综述_偏振光学成像去雾技术综述
  19. 【SW系列】计算机案例之草图文字
  20. 基于Auto.js的蚂蚁森林能量收集脚本

热门文章

  1. 肠道微生物群与心血管疾病:机遇与挑战
  2. python语言的语法_Python第一章基本语言语法
  3. 使用uniapp做微信小程序,在小程序编辑器运行时编译报错:appid不合法,导致启用不了。
  4. python股票查询系统_使用python获取股票的上市日期等基本信息
  5. 求一元二次方程的根(YZOJ-1048)
  6. 程序员的薪资为什么这么高?
  7. 怎么可以修改pr基本图形中的文字_10、Pr中基本图形安装使用,点点就可以应用高级的字幕...
  8. [Spring Boot] 2. Spring Boot 启动过程定制化
  9. 水安ABC考试多选练习题库(6)
  10. 2021全国特种设备-Q2桥式起重机司机模拟考试题库一[安考星]