iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >怎么用javaweb实现在线聊天工具
  • 310
分享到

怎么用javaweb实现在线聊天工具

2023-06-17 06:06:28 310人浏览 独家记忆
摘要

本篇内容主要讲解“怎么用javaweb实现在线聊天工具”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么用javaWEB实现在线聊天工具”吧!写这个玩意儿就是想练练手, 用户需要登陆才能在线聊天

本篇内容主要讲解“怎么用javaweb实现在线聊天工具”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么用javaWEB实现在线聊天工具”吧!

写这个玩意儿就是想练练手, 用户需要登陆才能在线聊天,不要依赖数据库, 不需要数据库的操作, 所有的数据都是保存在内存中, 如果服务器一旦重启,数据就没有了;

登录界面:

怎么用javaweb实现在线聊天工具

聊天界面:

怎么用javaweb实现在线聊天工具

左侧是在线的用户列表, 右侧是聊天的内容, 内容的格式为 “作者 : 内容”;

点击button可以发布聊天信息;

使用的是spring搭建的框架,基于Tomcat服务器

web.xml的配置如下:

<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0"      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_3_0.xsd">   <display-name></display-name>       <welcome-file-list>     <welcome-file>index.htm</welcome-file>   </welcome-file-list>      <servlet>     <servlet-name>test</servlet-name>     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>     <load-on-startup>1</load-on-startup>     </servlet>      <servlet-mapping>     <servlet-name>test</servlet-name>     <url-pattern>*.htm</url-pattern>     </servlet-mapping>      <listener>         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>     </listener>          <filter>         <filter-name>CharacterEncodingFilter</filter-name>         <filter-class>com.nono.Filter.CharacterEncodingFilter</filter-class>         <init-param>             <param-name>encoding</param-name>             <param-value>UTF-8</param-value>         </init-param>     </filter>          <filter>           <filter-name>SecurityServlet</filter-name>           <filter-class>com.nono.SecurityServlet</filter-class>       </filter>       <filter-mapping>           <filter-name>SecurityServlet</filter-name>           <url-pattern>*.htm</url-pattern>       </filter-mapping>           <!--          使用Spring中的过滤器解决在请求和应答中的中文乱码问题      <filter>         <filter-name>characterEncodingFilter</filter-name>         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>         <init-param>             <param-name>encoding</param-name>             <param-value>utf-8</param-value>         </init-param>         <init-param>                 强制转换编码(request和response均适用)              <param-name>ForceEncoding</param-name>             <param-value>true</param-value>         </init-param>     </filter>     -->         <context-param>         <param-name>         contextConfigLocation         </param-name>         <param-value>         /WEB-INF/test-servlet.xml         </param-value>     </context-param> </web-app>

conteConfigLocation的配置为:

<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  xmlns:context="http://www.springframework.org/schema/context"  xmlns:aop="http://www.springframework.org/schema/aop"  xmlns:tx="http://www.springframework.org/schema/tx"  xmlns:mvc="http://www.springframework.org/schema/mvc"  xmlns:task="http://www.springframework.org/schema/task"  xsi:schemaLocation="http://www.springframework.org/schema/beans       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd       http://www.springframework.org/schema/context       http://www.springframework.org/schema/context/spring-context-3.0.xsd       http://www.springframework.org/schema/tx       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd       http://www.springframework.org/schema/aop       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd       http://www.springframework.org/schema/mvc       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd       http://www.springframework.org/schema/task       http://www.springframework.org/schema/task/spring-task-3.0.xsd">           <context:annotation-config> </context:annotation-config>     <context:component-scan base-package="com.nono" > </context:component-scan>          <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">         <property name="suffix">             <value>.jsp</value>         </property>     </bean> </beans>

整个项目的结构为一个主路由, 四个po层,  两个过滤器:

怎么用javaweb实现在线聊天工具

界面的用户列表和用户内容列表用了ajax刷新, 感觉不错的说:

<!--     修改pageEncoding为 utf-8  --> <%@ 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>login</title>     <meta charset="utf-8">     <link href="http://cdn.bootCSS.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">     <script src="http://cdn.bootcss.com/Jquery/1.9.0/jquery.js"></script>   </head>   <style>       html,body,.bg{           height:100%;       }       .bg{           background:url(imgs/bg.jpeg);       }   </style>   <body>         <div class="container-fuild bg">             <div class="row">                 <div class="col-sm-4">                     <div class="page-header">                         <h3>                             list                         </h3>                         <ol id="list">                             <li>name—</li>                             <li>name—</li>                             <li>name—</li>                             <li>name—</li>                         </ol>                     </div>                 </div>                 <div class="col-sm-8">                         <h3>                             content                         </h3>                     <div id="con" class="page-header">                       <p>                           <b>haha:</b>                           <big>                               say someting                           </big>                       </p>                       <p>                           <b>haha:</b>                           <big>                               say someting                           </big>                       </p>                     </div>                     <fORM>                       <div class="form-group">                         <label for="text">enter text</label>                         <input type="text" id="answer" class="form-control" id="text" placeholder="text">                       </div>                       <button type="button" id="sb" class="btn btn-default">Submit</button>                     </form>                 </div>             </div>         </div>         <script>             $("#sb").click(function() {                 $.post("chat.htm", "content="+ $("#answer").val(), function(data) {                     console.log(data);                 });             });                          function Get(url , el, fn) {                 this.post = function() {                     $.post(url, function(data) {                         data = JSON.parse(data);                         var html = "";                         $.each(data,function(i, e) {                             html += fn(i,e);                         });                         $(el).html( html );                     });                 };             };                          (function() {                              var list = new Get("getList.htm", "#list", function(i, e) {                     return  "<li>" + e.name + "</li>";                 });                                  var content =  new Get("getContent.htm", "#con", function(i, e) {                     return "<p><b>"+ e.name +" : </b><big>"+ e.content +"</big></p>";                 });                                  setInterval(function() {                     list.post();                     content.post();                 },1000);                              })();         </script>   </body> </html>

权限控制的话我们可以用到fileter:

package com.nono;  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; import javax.servlet.http.httpservlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;  import com.nono.po.User;  public class SecurityServlet extends HttpServlet implements Filter {     private static final long serialVersionUID = 1L;      public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {            HttpServletRequest request=(HttpServletRequest)arg0;               HttpServletResponse response  =(HttpServletResponse) arg1;                HttpSession session = request.getSession();            User user = (User) session.getAttribute("user");            String url=request.getRequestURI();               //如果用户信息不是空的, 或者要访问的是登陆的界面(get,post的方式包含了login字符串);            if( user!=null  || url.indexOf("login")>-1 ) {                arg2.doFilter(arg0, arg1);                   return;            }else{                //余下的全跳到登陆界面                response.sendRedirect(request.getContextPath() + "/login.htm");                return;            }     }     public void init(FilterConfig arg0) throws ServletException {     }  }

路由控制和服务放到了一起, 因为权限控制使用过滤器处理, 所以在路由里面我们就不用关心用户的消息, 只要处理业务逻辑就好了:

package com.nono.Controller;  import java.util.ArrayList; import java.util.HashMap; import java.util.Vector;  import javax.jms.Session; import javax.print.DocFlavor.STRING; import javax.print.attribute.HashAttributeSet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;  import net.sf.json.JSONArray;  import org.omg.CORBA.PUBLIC_MEMBER; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody;  import com.nono.po.Content; import com.nono.po.Contents; import com.nono.po.User; import com.nono.po.Users;  @Controller public class MainController {     //用户和用户组;     @Autowired     Users users;          @Autowired     Contents contents;          @RequestMapping(value="login", method=RequestMethod.GET)     public String login (HttpServletRequest request) {         return "login";     }           @RequestMapping(value="login", method=RequestMethod.POST)     public String loginPOST ( HttpServletRequest request, HttpServletResponse response ) {                  String string = "login";         String name = (String) request.getParameter("name");         Boolean flag = true;         //如果名字不是空的话;         if( !name.equals("") ) {             Vector vector = users.getList();             for(int i=0; i< vector.size(); i++) {                 User user = (User) vector.elementAt(i);                 if( user.getName().equals( name ) ) {                     flag = false;                 };             };         };                  //用户名不存在         if( flag ) {             User user = new User();             user.setName( name );             HttpSession session = request.getSession(true);             //设置Session的过期时间为10分钟             session.setMaxInactiveInterval(600);             //设置seesion中的用户信息;             session.setAttribute("user", user);             //添加用户;             users.addUser( user );                          //加入的提示;             Content content = new Content();             content.setName( name );             content.setContent( "enter the chat room!" );             contents.addContent( content  );                          string = "chat";             return string;         }else{             //用户名已经存在             request.setAttribute("info", "用户名已经存在1");             string = "login";             return string;         }     }          @RequestMapping(value="chat", method=RequestMethod.GET)     public String main (HttpServletRequest request) {         String string = "chat";         return string;     }          @RequestMapping(value="chat", method=RequestMethod.POST)     @ResponseBody     public String chat(HttpServletRequest request) {         String string = (String) request.getParameter("content");         HttpSession session = request.getSession();         //设置seesion中的用户信息;         User user = (User) session.getAttribute("user");         String name = user.getName();         Content content = new Content();         content.setName( name );         content.setContent( string );         contents.addContent( content  );         return "true";     }          @RequestMapping(value="getList", method=RequestMethod.POST, produces = "text/html;charset=UTF-8")     @ResponseBody     public String getList( HttpServletRequest request) {         return JSONArray.fromObject( users.getList() ).toString();     }          @RequestMapping(value="getContent", method=RequestMethod.POST, produces = "text/html;charset=UTF-8")     @ResponseBody     public String getArrayList() {         ArrayList list = (ArrayList) contents.getContents();         ArrayList result = new ArrayList();         for( int i= 0; i< list.size(); i++ ) {             HashMap<String,String> hashMap = new HashMap();             hashMap.put("name", ((Content)list.get(i)).getName());             hashMap.put("content", ((Content)list.get(i)).getContent());             result.add( hashMap );         };         return JSONArray.fromObject( result ).toString();     }      }

到此,相信大家对“怎么用javaweb实现在线聊天工具”有了更深的了解,不妨来实际操作一番吧!这里是编程网网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

--结束END--

本文标题: 怎么用javaweb实现在线聊天工具

本文链接: https://www.lsjlt.com/news/287458.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 怎么用javaweb实现在线聊天工具
    本篇内容主要讲解“怎么用javaweb实现在线聊天工具”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么用javaweb实现在线聊天工具”吧!写这个玩意儿就是想练练手, 用户需要登陆才能在线聊天...
    99+
    2023-06-17
  • Python怎么实现在线聊天室私聊
    本篇内容主要讲解“Python怎么实现在线聊天室私聊”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Python怎么实现在线聊天室私聊”吧!实现思路对于私聊,我觉得应该有如下两点需要实现私聊列表更...
    99+
    2023-06-02
  • java实现多人聊天工具(socket+多线程)
    大一下学期的java期末课程设计:java实现多人聊天工具,分享一下 课设要求 多人聊天工具 服务器要求1:能够看到所有在线用户(25%) 服务器要求2:能够强制用...
    99+
    2024-04-02
  • SpringBoot+WebSocket怎么实现在线聊天
    本篇内容主要讲解“SpringBoot+WebSocket怎么实现在线聊天”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“SpringBoot+WebSocket怎么实现在线聊天”吧!在线聊天使用...
    99+
    2023-06-19
  • Go语言怎么实现聊天小工具
    本篇内容介绍了“Go语言怎么实现聊天小工具”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!代码实现server.gopackage ...
    99+
    2023-07-05
  • php如何实现聊天工具
    小编给大家分享一下php如何实现聊天工具,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!php实现聊天工具的方法:1、执行函数set_chat_msg;2、在服务器...
    99+
    2023-06-25
  • Java实现简单QQ聊天工具
    Java实现简单的类似QQ聊天工具,供大家参考,具体内容如下 所使用到的知识点: java socket编程之TCP协议java Swing简单的java多线程 运行截图: 服务...
    99+
    2024-04-02
  • 怎么用Go语言实现UDP版聊天小工具
    这篇文章主要介绍“怎么用Go语言实现UDP版聊天小工具”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“怎么用Go语言实现UDP版聊天小工具”文章能帮助大家解决问题。代码实现server.gopacka...
    99+
    2023-07-05
  • java实现在线聊天系统
    本文实例为大家分享了java实现在线聊天系统的具体代码,供大家参考,具体内容如下 本博客是博主在观看相关视频后写下的代码,希望能够帮助大家掌握java socket的相关知识。 原理...
    99+
    2024-04-02
  • Java实现在线聊天功能
    本文实例为大家分享了Java实现在线聊天功能的具体代码,供大家参考,具体内容如下 效果 关键代码 创建Client.java import java.io.IOException;...
    99+
    2024-04-02
  • Node.js怎么实现在线实时多人聊天室
    本篇内容介绍了“Node.js怎么实现在线实时多人聊天室”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!文件结构如下:前端部分:登录页面Log...
    99+
    2023-07-04
  • Springboot+WebSocket实现在线聊天功能
    目录一、后端二、Websocket三、前端一、后端 1.在Springboot项目的pom.xml中添加依赖 <!--websocket协议--> <depende...
    99+
    2023-02-14
    Springboot WebSocket在线聊天 Springboot WebSocket聊天 Springboot WebSocket
  • Unity实现简单的多人聊天工具
    本文实例为大家分享了Unity实现多人聊天工具的具体代码,供大家参考,具体内容如下 代码1 : 服务端代码 using UnityEngine; using System.Net.S...
    99+
    2024-04-02
  • vue实现web在线聊天功能
    本文实例为大家分享了vue实现web在线聊天的具体代码,供大家参考,具体内容如下 最终实现的效果 实现过程 无限滚动窗体的实现之前已经介绍过,这里就不在赘述了,不清楚的可以通过文档...
    99+
    2024-04-02
  • Vue+ssh框架实现在线聊天
    本文实例为大家分享了Vue+ssh框架实现在线聊天的具体代码,供大家参考,具体内容如下 效果图 核心部分 websocket编程 向后台发送消息 <template&...
    99+
    2024-04-02
  • Node.js+express+socket怎么实现在线实时多人聊天室
    本文小编为大家详细介绍“Node.js+express+socket怎么实现在线实时多人聊天室”,内容详细,步骤清晰,细节处理妥当,希望这篇“Node.js+express+socket怎么实现在线实时多人聊天室”文章能帮助大家解决疑惑,下...
    99+
    2023-06-17
  • C#基于UDP实现的P2P语音聊天工具
    今天就跟大家聊聊有关C#基于UDP实现的P2P语音聊天工具,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。主要是一个应用,使用udp传送语音和文本等信息。在这个系统中没有服务端和客户端...
    99+
    2023-06-17
  • 怎么在Django中使用channels和websocket实现一个在线聊天室
    本篇文章为大家展示了怎么在Django中使用channels和websocket实现一个在线聊天室,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。Channels是Django团队研发的一个给Djan...
    99+
    2023-06-15
  • 【uni-app】小程序实现微信在线聊天(私聊/群聊)
    之前学习使用uni-app简单实现一个在线聊天的功能,今天记录一下项目核心功能的实现过程。页面UI以及功能逻辑全部来源于微信,即时聊天业务的实现使用socket.io,前端使用uni-app开发,后端服务器基于node实现,数据库选择mon...
    99+
    2023-09-03
    uni-app 前端 小程序
  • Java实现在线聊天室(层层递进)
    本文实例为大家分享了Java实现在线聊天室的具体代码,供大家参考,具体内容如下 - 本文讲述了从实现单个多个客户的收发信息(基础简易版),到各种实现代码的封装(oop版),实现群聊(...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作