springboot md5加密_實在!基于Springboot和WebScoket,寫了一個在線聊天小程序

基于Springboot和WebScoket寫的一個在線聊天小程序

(好幾天沒有寫東西了,也沒有去練手了,就看了看這個。。。)

0603d08be2666b0739fb11eda4f0dda1.png

項目說明

  • 此項目為一個聊天的小demo,采用springboot+websocket+vue開發。
  • 其中有一個接口為添加好友接口,添加好友會判斷是否已經是好友。
  • 聊天的時候:A給B發送消息如果B的聊天窗口不是A,則B處會提醒A發來一條消息。
  • 聊天內容的輸入框采用layui的富文本編輯器,目前不支持回車發送內容。
  • 聊天可以發送圖片,圖片默認存儲在D:/chat/目錄下。
  • 點擊聊天內容中的圖片會彈出預覽,這個預覽彈出此條消息中的所有圖片。
  • 在發送語音的時候,語音默認發送給當前聊天窗口的用戶,所以錄制語音的時候務必保證當前聊天窗口有選擇的用戶。
  • 知道用戶的賬號可以添加好友,目前是如果賬號存在,可以直接添加成功

老規矩,還是先看看小項目的目錄結構:

efec7d2fe799de43713cd61aae83fd6b.png

一、先引入pom文件

這里就只放了一點點代碼(代碼太長了)

commons-io            commons-io            2.4org.projectlombok            lombok        net.sf.json-lib            json-lib            2.4jdk15org.springframework.boot            spring-boot-starter-thymeleaf            2.2.4.RELEASEcom.alibaba            fastjson            1.2.60org.springframework.boot            spring-boot-starter-test            test

二、創建對應的yml配置文件

spring:  profiles:    active: prod
spring:  datasource:    username: root    password: root    url: jdbc:mysql://localhost:3306/chat?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&serverTimezone=UTC    driver-class-name: com.mysql.jdbc.Driver    #指定數據源    type: com.alibaba.druid.pool.DruidDataSource    # 數據源其他配置    initialSize: 5    minIdle: 5    maxActive: 20    maxWait: 60000    timeBetweenEvictionRunsMillis: 60000    minEvictableIdleTimeMillis: 300000    validationQuery: SELECT 1    testWhileIdle: true    testOnBorrow: false    testOnReturn: false    poolPreparedStatements: true    #   配置監控統計攔截的filters,去掉后監控界面sql無法統計,'wall'用于防火墻    filters: stat,log4j    maxPoolPreparedStatementPerConnectionSize: 20    useGlobalDataSourceStat: true    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500  thymeleaf:    suffix: .html    prefix:      classpath: /templates/    cache: false  jackson: #返回的日期字段的格式    date-format: yyyy-MM-dd HH:mm:ss    time-zone: GMT+8    serialization:      write-dates-as-timestamps: false # true 使用時間戳顯示時間  http:    multipart:      max-file-size: 1000Mb      max-request-size: 1000Mb#配置文件式開發mybatis:  #全局配置文件的位置  config-location: classpath:mybatis/mybatis-config.xml  #所有sql映射配置文件的位置  mapper-locations: classpath:mybatis/mapper/**/*.xmlserver:  session:    timeout: 7200

三、創建實體類

這里就不再多說了,有Login,Userinfo,ChatMsg,ChatFriends

abcdb344c033cbd5081b3e2cccaaaaed.png

四、創建對應的mapper(即dao層)還有對應的mapper映射文件

(這里就舉出了一個,不再多說)

public interface ChatFriendsMapper {    //查詢所有的好友    List LookUserAllFriends(String userid);    //插入好友    void InsertUserFriend(ChatFriends chatFriends);    //判斷是否加好友    Integer JustTwoUserIsFriend(ChatFriends chatFriends);    //查詢用戶的信息    Userinfo LkUserinfoByUserid(String userid);}
<?xml version="1.0" encoding="UTF-8"?>      select userid,nickname,uimg from userinfo where userid in (select a.fuserid from chat_friends a where a.userid=#{userid})            insert into chat_friends (userid, fuserid) value (#{userid},#{fuserid})            select id from chat_friends where userid=#{userid} and fuserid=#{fuserid}            select * from userinfo where userid=#{userid}    

五、創建對應的業務類(即service)

(同樣的業務層這里也就指出一個)

@Servicepublic class ChatFriendsService {    @Autowired    ChatFriendsMapper chatFriendsMapper;    public List LookUserAllFriends(String userid){        return chatFriendsMapper.LookUserAllFriends(userid);    }    public void InsertUserFriend(ChatFriends chatFriends){        chatFriendsMapper.InsertUserFriend(chatFriends);    }    public Integer JustTwoUserIsFriend(ChatFriends chatFriends){        return chatFriendsMapper.JustTwoUserIsFriend(chatFriends);    }    public Userinfo LkUserinfoByUserid(String userid){        return chatFriendsMapper.LkUserinfoByUserid(userid);    }}

六、創建對應的控制器

這里再說說項目的接口

  1. /chat/upimg 聊天圖片上傳接口
  2. /chat/lkuser 這個接口用來添加好友的時候:查詢用戶,如果用戶存在返回用戶信息,如果不存在返回不存在
  3. /chat/adduser/ 這個接口是添加好友接口,會判斷添加的好友是否是自己,如果添加的好友已經存在則直接返回
  4. /chat/ct 跳轉到聊天界面
  5. /chat/lkfriends 查詢用戶的好友
  6. /chat/lkuschatmsg/ 這個接口是查詢兩個用戶之間的聊天信息的接口,傳入用戶的userid,查詢當前登錄用戶和該用戶的聊天記錄。
  7. /chat/audio 這個接口是Ajax上傳web界面js錄制的音頻數據用的接口

(同樣就只寫一個)

@Controllerpublic class LoginCtrl {    @Autowired    LoginService loginService;    @GetMapping("/")    public String tologin(){        return "user/login";    }    /**     * 登陸     * */    @PostMapping("/justlogin")    @ResponseBody    public R login(@RequestBody Login login, HttpSession session){        login.setPassword(Md5Util.StringInMd5(login.getPassword()));        String userid = loginService.justLogin(login);        if(userid==null){            return R.error().message("賬號或者密碼錯誤");        }        session.setAttribute("userid",userid);        return R.ok().message("登錄成功");    }}

七、創建對應的工具類以及自定義異常類

  1. 表情過濾工具類
public class EmojiFilter {    private static boolean isEmojiCharacter(char codePoint) {        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)                || (codePoint == 0xD)                || ((codePoint >= 0x20) && (codePoint <= 0xD7FF))                || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))                || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));    }    @Test    public void testA(){        String s = EmojiFilter.filterEmoji("您好,你好啊");        System.out.println(s);    }
  1. Md5數據加密類
   static String[] chars = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};    /**     * 將普通字符串用md5加密,并轉化為16進制字符串     * @param str     * @return     */    public static String StringInMd5(String str) {        // 消息簽名(摘要)        MessageDigest md5 = null;        try {            // 參數代表的是算法名稱            md5 = MessageDigest.getInstance("md5");            byte[] result = md5.digest(str.getBytes());            StringBuilder sb = new StringBuilder(32);            // 將結果轉為16進制字符  0~9 A~F            for (int i = 0; i < result.length; i++) {                // 一個字節對應兩個字符                byte x = result[i];                // 取得高位                int h = 0x0f & (x >>> 4);                // 取得低位                int l = 0x0f & x;                sb.append(chars[h]).append(chars[l]);            }            return sb.toString();        } catch (NoSuchAlgorithmException e) {            throw new RuntimeException(e);        }    }
  1. 測試數據加密類
public class TestUtil {    @Test    public void testA(){        String s = Md5Util.StringInMd5("123456");        System.out.println(s);    }}

八、引入對應的靜態資源文件(這個應該一開始就做的)

a68e2dd982535286b954c9757b95b96d.png

九、自定義一些配置并且注入到容器里面

  1. Druid數據源
@Configurationpublic class DruidConfig {    @ConfigurationProperties(prefix = "spring.datasource")    @Bean    public DataSource druid(){        return new DruidDataSource();    }    //配置Druid的監控    //1.配置要給管理后臺的Servlet    @Bean    public ServletRegistrationBean servletRegistrationBean(){        ServletRegistrationBean bean=new ServletRegistrationBean(new StatViewServlet(),"/druid/*");        Map initParams=new HashMap<>();        initParams.put("loginUsername","admin");        initParams.put("loginPassword","admin233215");        initParams.put("allow","");//默認允許ip訪問        initParams.put("deny","");        bean.setInitParameters(initParams);        return bean;    }    //2.配置一個監控的filter    @Bean    public FilterRegistrationBean webStarFilter(){        FilterRegistrationBean bean=new FilterRegistrationBean();        bean.setFilter(new WebStatFilter());        Map initParams=new HashMap<>();        initParams.put("exclusions","*.js,*.css,/druid/*");        bean.setInitParameters(initParams);        bean.setUrlPatterns(Arrays.asList("/*"));        return bean;    }}
  1. 靜態資源以及攔截器
@Configurationpublic class MyConfig extends WebMvcConfigurerAdapter {    //配置一個靜態文件的路徑 否則css和js無法使用,雖然默認的靜態資源是放在static下,但是沒有配置里面的文件夾    @Override    public void addResourceHandlers(ResourceHandlerRegistry registry) {        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");    }    @Bean    public WebMvcConfigurerAdapter WebMvcConfigurerAdapter() {        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {            @Override            public void addResourceHandlers(ResourceHandlerRegistry registry) {                //registry.addResourceHandler("/pic/**").addResourceLocations("file:D:/chat/");                registry.addResourceHandler("/pic/**").addResourceLocations("file:D:/idea_project/SpringBoot/Project/Complete&&Finish/chat/chatmsg/");                super.addResourceHandlers(registry);            }        };        return adapter;    }    @Override    public void addInterceptors(InterceptorRegistry registry) {        //注冊TestInterceptor攔截器        InterceptorRegistration registration = registry.addInterceptor(new AdminInterceptor());        registration.addPathPatterns("/chat/*");    }}
  1. WebSocketConfigScokt通信配置
@Configuration@EnableWebSocketpublic class WebSocketConfig {     @Bean    public ServerEndpointExporter serverEndpointExporter() {        return new ServerEndpointExporter();    }}

十、進行測試

這是兩個不同的用戶

29f6d07cb3bf5002ff93f61d3ed0da29.png
f85fbe356dc8fbc1767ba723ce014274.png

當然了,還可以進行語音,添加好友 今天的就寫到這里吧!謝謝! 這里要提一下我的一個學長的個人博客,當然了,還有我的,謝謝

作者:奶思

鏈接:https://juejin.im/post/5ea7994c5188256da14e972d

來源:掘金

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/396881.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/396881.shtml
英文地址,請注明出處:http://en.pswp.cn/news/396881.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

suse 啟動oracle11g,SuSe10下Oracle11g文件系統模式安裝及配置、網絡配置與連接

SuSe10下Oracle11g文件系統模式安裝及配置、網絡配置與連接概述本課程主要講解oracle數據庫軟件的安裝及配置&#xff0c;以及數據庫的創建過程和網絡配置與連接等&#xff1b;同時講解一些數據庫安裝過程中的常見問題解決辦法。注意&#xff1a;本文當中引用的package_name均為…

Python pyenv

一、簡介 一般在操作系統中我們會安裝多個Python版本&#xff0c;所以在進行Python版本切換時會比較麻煩&#xff0c;pyenv就提供了一種簡單的方式&#xff0c;能簡易地在多個Python版本中進行切換的工具&#xff0c;它簡單而優雅。pyenv有以下功能&#xff1a; 1&#xff09;進…

python中add_Python add()函數是如何使用呢?

Python里經常會出現一些不太常見的函數&#xff0c;大家在遇到這類函數時候&#xff0c;是怎么做的呢&#xff1f;沒有概念&#xff0c;直接過&#xff0c;還是會去查詢下呢&#xff1f;相信大部分人都不會去查詢&#xff0c;因為查詢的內容太復雜了&#xff0c;所以&#xff0…

JavaScript的DOM編程總結

DOM&#xff08;文檔對象模型&#xff09;, 與語言無關, 用于操作XML&#xff08;在Web中&#xff09;和HTML&#xff08;在瀏覽器在&#xff09;文檔的應用程序接口。訪問DOM次數越多, 速度越慢, 費用也就越高。 最小化DOM訪問次數&#xff0c;盡可能在JavaScript端處理。 如果…

2017.1.20活動

1、根據教程用傾斜開關控制了一個小燈的亮滅&#xff08;傾斜到達一定角度亮或到達一定角度滅&#xff09;&#xff0c;后自己嘗試了利用傾斜開關控制兩個小燈&#xff0c;即一開始綠燈亮紅燈滅&#xff0c;到達一定角度后&#xff0c;綠燈亮起紅燈滅掉&#xff0c;附代碼&…

oracle 增加間隔分區,oracle分區表之間隔分區(oracle 11g) - 漫兮網

范圍分區允許用戶根據分區鍵列值的范圍創建分區。下面是一個按范圍分區表的示例&#xff1a;create table sales6(sales_id number,sales_dt date)partition by range (sales_dt)(partition p0701 values less than (to_date(2007-02-01,yyyy-mm-dd)),partition p0702 values l…

c++ try catch語句_再問你一遍,你真的了解try..catch(finally)嗎???

定義首先來看下 MDN 的定義&#xff1a;The try...catch statement marks a block of statements to try and specifies a response should an exception be thrown.try...catch語句標記要執行的語句&#xff0c;并指定一個當有異常拋出時候的響應簡短的一句的確描述了try...ca…

lamp架構,搭建一個網絡平臺

首先更改主機名和 hosts 安裝軟件包&#xff0c;設置啟動服務 設置數據庫密碼 上傳discuz論壇包 將discuz注冊的用戶名寫在mariadb數據庫中 解壓discuz包 unzip discuz包 -d /var/www/html cd到upload下 cp -rf * /var/www/html 進入數據庫 mysql -uroot -p create database…

MyEclipse中SVN的使用方法

1、 加載插件 svn-myeclipse插件site-1.10.2.zip&#xff0c;解壓縮后&#xff0c;將文件夾下的所有文件拷貝到MyEclipse安裝包下的MyEclipse 8.5\dropins文件夾下&#xff0c;然后重新打開myeclipse&#xff0c;會彈出一個報錯窗口&#xff0c;不要管它&#xff0c;關閉后&…

oracle數據泵導出csv文件,數據泵expdp導出遇到ORA-01555和ORA-22924問題的分析和處理...

使用數據泵導出數據庫數據時&#xff0c;發現如下錯誤提示&#xff1a;ORA-31693: Table data object "CAMS_CORE"."BP_EXCEPTION_LOG" failed to load/unload and is being skipped due to error:ORA-02354: error in exporting/importing dataORA-01555:…

Go程序開發---Go環境配置:CentOS6.5+Go1.8標準包安裝

1.Go安裝 1.1Go的三種安裝方式 Go有多種安裝方式&#xff0c;可以選擇自己習慣的方式進行&#xff0c;這里介紹三種安裝方式&#xff1a; 1&#xff09;Go源碼安裝 2&#xff09;Go標準包安裝 3&#xff09;第三方工具安裝 這里主要介紹下Go標準包在CentOS6.5系統中的安裝方式 …

python矩陣乘法_魚書——第一章 Python入門

one 第一章1.1 Python是什么Python是一個簡單、易讀、易記的編程語言&#xff0c;而且是開源的&#xff0c;可以免費地自由使用。Python可以用類似英語的語法編寫程序&#xff0c;編譯起來也不費力&#xff0c;因此我們可以很輕松地使用Python。特別是對首次接觸編程的人士來說…

深入淺出面向對象分析與設計

深入淺出面向對象分析與設計書籍 下載位置&#xff1a;http://pan.baidu.com/s/1o7gmmuu轉載于:https://www.cnblogs.com/wlming/p/5160140.html

[SHOI2002]百事世界杯之旅

題目&#xff1a;“……在2002年6月之前購買的百事任何飲料的瓶蓋上都會有一個百事球星的名字。只要湊齊所有百事球星的名字&#xff0c;就可參加百事世界杯之旅的抽獎活動&#xff0c;獲得球星背包&#xff0c;隨聲聽&#xff0c;更克赴日韓觀看世界杯。還不趕快行動&#xff…

Oracle adviser,Oracle10g SQL tune adviser

Oracle10g SQL tune adviser簡單介紹本文簡單介紹下SQL Tuning Adviser的配置使用方法和一些相關知識點&#xff0c;如果了解SQL Tuning Adviser詳細信息&#xff0c;參看Oracle聯機文檔。本文對分析結果沒有詳細分析。一、自動SQL Tuning簡單介紹&#xff1a;1、優化模式&…

考托福

todo 香港的博士 轉載于:https://www.cnblogs.com/dunfentiao/p/5164028.html

keepalived vip ping不通_【干貨分享】OpenStack LVS負載均衡為什么不通?

背景介紹OpenStack環境Neutron 的安全組會向虛擬機默認添加 anti-spoof 的規則&#xff0c;將保證虛擬機只能發出&#xff0f;接收以本機Port為原地址或目的地址(IP、MAC)的流量&#xff0c;提高了云的安全性。但是LVS等需要綁定VIP的場景&#xff0c;默認流量是被攔截的。需要…

Docker安裝ssh,supervisor等基礎工具

2019獨角獸企業重金招聘Python工程師標準>>> Docker安裝ssh&#xff0c;supervisor等基礎工具 需要提前下載好官方的ubuntu鏡像&#xff0c;我這里使用的是ubuntu:14.04版本&#xff0c;這里安裝了一些基礎的工具ssh&#xff0c;curl&#xff0c;wget&#xff0c;vi…

中南大學 oracle試卷,數據庫原理期末復習(中南大學)數據庫原理、技術及應用2.ppt...

2014 春季 信息11,12 DB P,T&A-張祖平 數據庫原理、技術及應用 張祖平/Zhang Zuping 電子信息工程系 School of Information Science and Engineering,Central South University , zpzhangmail.csu.edu.cn 本章小結 關系模型中的相關概念 關系(集合)&#xff0c;性質&#…

Pandas時間差(Timedelta)

時間差(Timedelta)是時間上的差異&#xff0c;以不同的單位來表示。例如&#xff1a;日&#xff0c;小時&#xff0c;分鐘&#xff0c;秒。它們可以是正值&#xff0c;也可以是負值。可以使用各種參數創建Timedelta對象&#xff0c;如下所示 - 字符串 通過傳遞字符串&#xff0…