Springboot+Vue实现在线聊天室项目
该聊天室为大二上学期计算机网络大作业,并且是本人第一次使用vue实现前后端分离的项目,前端架构尚未熟悉可能会出现一些不妥之处,还请大佬们指出。(本文章写于项目整体完成上线之后,所以一些细节并未写出)
获取房间信息在前端Home页调用,获取房间内消息在前端Home子路由chat页调用。
获取房间信息
Controller
@ResponseBody
@RequestMapping("/getRooms")
public Result getRoomIdByNames(String[] names){
return userService.getRooms();
}
Service
public Result getRooms(){
Result result = new Result();
try{
int uid = getUserIdCurrent();
System.out.println(uid);
ArrayList<Room> rooms = userDao.getRooms(uid);
System.out.println(rooms.toString());
result.setObj(rooms);
result.setMsg("获取成功");
result.setStatus(200);
}catch (Exception e){
e.printStackTrace();
result.setMsg("出现异常");
result.setStatus(402);
}
return result;
}
Dao
@Select("\n" +
"select a.name,a.roomId,a.img,message.msg,a.last,a.tips from message,(\n" +
"select a.name,a.id as roomId,a.img,msg,date,sum(message.date > b.lastlogindate) as tips ,max(message.date) as last from message,\n" +
"(select name,room.id,img from room where uids LIKE CONCAT(CONCAT('%|', #{uid}),'|%')\n" +
"order by lastDate desc)a,(select lastlogindate from user where user.id = #{uid})b\n" +
"where a.id = message.roomId \n" +
"group by roomId\n" +
")a where message.date = a.last")
public ArrayList<Room> getRooms(@Param("uid") int uid);
sql语句实现了:通过房间信息和用户上次登录时间获取登录时间后的房间消息,计数以tips的形式放回(就是未读消息数),所有房间信息排序由房间内最后一条消息的时间决定。
分页获取消息
Controller
@ResponseBody
@GetMapping("/getMsgByRoomId")
public Result getMsgByRoomId(int id,int page){
return userService.getMsgByRoomId(id,(page-1)*15);
}
Service
public Result getMsgByRoomId(int id,int limit){
Result result = new Result();
int uid = getUserIdCurrent();
String roomAuth = userDao.getRoomAuth(id);
String[] auths = roomAuth.split("|");
for (String auth:auths) {
if (auth.equals(uid + "")) {
result.setObj(userDao.getMsgByRoomId(id,limit));
result.setStatus(200);
result.setMsg("获取成功!");
break;
}else{
result.setMsg("没有权限访问!");
result.setStatus(401);
}
}
return result;
}
Dao
@Select("select * from (select roomId,date,msg,uid,img,name from message where roomId = #{roomId} order by message.date desc limit #{limit},15)a order by a.date")
public ArrayList<Message> getMsgByRoomId(int roomId,int limit);
一个非常简单的分页实现(每一页15条消息),这里就不细说了