친구관련된 기능에 대해서 모두 생각해보았을때 필요한 기능은
● 친구 추가 요청
● 친구 삭제
● 친구 요청 수락
● 친구 요청 거부
● 친구 요청 취소
● 친구 추가
등등이 있다
친구 추가 요청은 저번 시간에 했으니
이제 사용자에게 친구 추가 요청을 보낸 유저들을 가져오는 함수와
사용자가 친구 추가 요청을 보낸 유저들을 가져오는 함수들을 만들고
수락 버튼을 누르면 친구가 되는 함수 거절버튼을 누르면 요청 테이블에서 삭제시키고
요청 취소버튼도 누르면 요청 테이블에서 삭제시키는 함수를 만들어보자
우선 받은 요청과 보낸 요청들을 볼수있는 jsp 페이지
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/view/layout/header.jsp" %>
<%@ include file="/WEB-INF/view/layout/friendHeader.jsp" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<div class="receive_friend">
<span class="receive_friend_title">받은 초대</span>
<input type="text" placeholder="받은 초대 이름으로 검색하기">
</div>
<c:forEach var="user" items="${waitList}">
<div class="profile_box" id="profile_${user.id}">
<img src="images/${user.uploadFilename}" class="user_img">
<span class="user_name">${user.nickname}</span>
<button class="accept_btn" id="accept" onclick="accept(${user})">수락</button>
<button class="refuse_btn" id="refuse" onclick="refuse(${user})">거절</button>
</div>
</c:forEach>
<div class="send_friend">
<span class="send_friend_title">보낸 초대</span>
<input type="text" placeholder="보낸 초대 이름으로 검색하기">
</div>
<c:forEach var="user" items="${sendList}">
<div class="profile_box" id="${user.id}_profile">
<img src="images/${user.uploadFilename}" class="user_img">
<span class="user_name">${user.nickname}</span>
<button class="cancel_btn" id="cancel" onclick="cancel(${user})">취소</button>
</div>
</c:forEach>
<script>
// 친구요청 수락시 친구추가처리
function accept(user) {
const profile = document.querySelector("#profile_" + user.id);
fetch("http://192.168.0.131:8080/friends/accept/" + user.id)
.then((response) => {
if(response.ok) {
profile.remove();
}
});
}
// 친구요청 거절시 요청테이블 삭제처리
function refuse(user) {
const profile = document.querySelector("#profile_" + user.id);
fetch("http://192.168.0.131:8080/friends/refuse/" + user.id)
.then((response) => {
if(response.ok) {
profile.remove();
}
});
}
// 친구요청 취소시 요청테이블 삭제처리
function cancel(user) {
const profile = document.querySelector("#profile_" + user.id);
fetch("http://192.168.0.131:8080/friends/cancel/" + user.id)
.then((response) => {
if(response.ok) {
profile.remove();
}
});
}
</script>
<%@ include file="/WEB-INF/view/layout/footer.jsp" %>
다음은 내 친구들을 관리할수있는 jsp 페이지
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/view/layout/header.jsp" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<link rel="stylesheet" href="../css/myFriendList.css"> <!-- 추가된 스타일 시트 -->
<div class="content">
<div class="friends_count">
<span>나의 친구 ${count}</span>
<button id="manage_friends" class="manage_fiends_btn">
<span>친구 목록 관리</span>
</button>
<button id="add_friends" class="add_friends_btn">
<span>친구 추가</span>
</button>
</div>
<div class="search_friend">
<input type="text" placeholder="이름으로 친구 검색">
</div>
<div id="state_online" class="state_block">온라인</div>
<c:forEach var="online" items="${onlineList}">
<div class="user_box">
<a class="select_overlay" href="/chat/profileInfo?id=${online.id}"></a>
<img src="images/${online.uploadFilename}">
<span>${online.nickname}</span>
</div>
</c:forEach>
<div id="state_offline" class="state_block">오프라인</div>
<c:forEach var="offline" items="${offlineList}">
<div class="user_box">
<a class="select_overlay" href="/chat/profileInfo?id=${offline.id}"></a>
<img src="images/${offline.uploadFilename}">
<span>${offline.nickname}</span>
</div>
</c:forEach>
</div>
<%@ include file="/WEB-INF/view/layout/footer.jsp" %>
친구 추가를 하기위해 친구 검색을 할수있는 jsp 페이지
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/findFriend.css">
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div class="content">
<div class="search-box">
<form action="/friends/findUser" method="POST">
<input type="text" placeholder="Search for friends" name="name">
<input type="hidden" value="0" name="pageNum">
</form>
</div>
<div class="search-result">
<c:forEach var="user" items="${userList}">
<div class="user-profile">
<a href="/chat/profileInfo?id=${user.id}">
<img src="/images/${user.uploadFileName}" alt="Profile Picture">
</a>
<div class="user-info">
<div class="user-name">
<a href="/chat/profileInfo?id=${user.id}">${user.nickname}</a>
</div>
</div>
</div>
</c:forEach>
</div>
<div class="page">
<c:if test="${current} != 1">
<form action="/friends/findUser?name=${name}&page=${current - 1}" method="post">
<button class="previous">
이전
</button>
</form>
</c:if>
<c:forEach var="i" begin="1" end="${pageSize}">
<ul class="pagination">
<li><a href="pagePost(${i})"
<c:if test="${current} == ${i}">class="current-page"</c:if>
>${i}</a>
</li>
</ul>
<c:if test="${current} != ${pageSize}">
<form action="/friends/findUser?name=${name}&page=${current + 1}" method="post">
<button class="next">
다음
</button>
</form>
</c:if>
</c:forEach>
</div>
</div>
<script>
function pagePost(page) {
let form = document.createElement('form');
form.setAttribute('method','post');
form.setAttribute('action','/user/findUser');
let pageNum = document.createElement('input');
pageNum.setAttribute('type','hidden');
pageNum.setAttribute('name','pageNum');
pageNum.setAttribute('value',page);
let name = document.createElement('input');
name.setAttribute('type', 'hidden');
name.setAttribute('name','name');
name.setAttribute('value',`${name}`);
form.appendChild(name);
form.appendChild(pageNum);
document.body.appendChild(form);
form.submit();
}
</script>
</body>
</html>
아래는 쿼리문 이다
아래는 쿼리문에게 파라미터를 전송할 서비스 함수
package com.example.demo.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.repository.UserRepository;
import com.example.demo.repository.model.User;
import lombok.RequiredArgsConstructor;
@Service
@RequiredArgsConstructor
public class FriendService {
private final UserRepository userRepository;
@Transactional
// 친구 검색기능
public List<User> findLikeUser(String nickname, int limit, int offset) {
List<User> userList = null;
userList = userRepository.findLikeNickname(nickname, limit, offset);
return userList;
}
public int findLikeUserSize(String nickname) {
int count = 0;
count = userRepository.findLikeNicknameSize(nickname);
return count;
}
public User findByUserID(int id) {
User user = userRepository.findByUserId(id);
return user;
}
public int insertWaitingFriend(int userId, int friendId) {
int result = userRepository.insertWatingFriend(userId, friendId);
return result;
}
// 친구요청 수락시 친구 추가
public int addFriend(int userId, int friendId) {
int result = 0;
result = userRepository.addFriendById(userId, friendId);
return result;
}
// 친구삭제시 삭제요청한 유저에게만 친구삭제
public int removeFriend(int userId, int friendId) {
int result = 0;
result = userRepository.removeFriendById(userId, friendId);
return result;
}
// 친구요청 취소 or 거절시 요청목록에서 삭제
public int removeWaitFriend(int userId, int friendId) {
int result = 0;
result = userRepository.removeWaitFriendById(userId, friendId);
return result;
}
// 친구요청 수락시 여전히 친구요청중인지 확인하기
public int checkWaitFriend(int userId, int friendId) {
int result = 0;
result = userRepository.checkWaitFriend(userId, friendId);
return result;
}
// 온라인인 친구 찾기
public List<User> checkOnlineFriend(int id) {
List<User>onlineFriendList = null;
int online = 1;
onlineFriendList = userRepository.checkStatusFriend(id, online);
return onlineFriendList;
}
// 오프라인인 친구 찾기
public List<User> checkOfflineFriend(int id) {
List<User>offlineFriendList = null;
int offline = 0;
offlineFriendList = userRepository.checkStatusFriend(id, offline);
return offlineFriendList;
}
// 사용자에게 친구요청을 보낸 유저 리스트
public List<User> checkWaitFriendList(int id) {
List<User>waitFriendList = null;
waitFriendList = userRepository.checkWaitFriend(id);
return waitFriendList;
}
// 사용자가 친구요청을 보낸 유저 리스트
public List<User> checkSendFriendList(int id) {
List<User>sendFriendList = null;
sendFriendList = userRepository.checkSendFriend(id);
return sendFriendList;
}
}
아래는 친구 카테고리에서 모든 요청을 처리할 컨트롤러이다
package com.example.demo.controller;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.example.demo.repository.model.User;
import com.example.demo.service.FriendService;
import com.example.demo.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
@Controller
@RequestMapping("/friends")
@RequiredArgsConstructor
public class FriendsController {
private final FriendService friendService;
private final HttpSession session;
// 친구 검색
@GetMapping("/findUser")
public String getMethodName() {
return "friend/findFriend";
}
// 검색 결과
@PostMapping("/findUser")
public String postMethodName(@RequestParam(name="name") String name,
@RequestParam(name="pageNum")int page , HttpServletRequest request) {
// 한 페이지에 유저가 10명씩 보이도록 설정
int limit = 10;
// 오프셋은 limit * (page - 1)
int offset = limit * (page - 1);
List<User>userList = friendService.findLikeUser(name,limit,offset);
int size = friendService.findLikeUserSize(name);
int pageNum = (int)Math.ceil(size / limit);
request.setAttribute("userList", userList); // 검색된 유저리스트
request.setAttribute("name", name); // 검색어
request.setAttribute("current",page); // 현재 페이지
request.setAttribute("pageSize", pageNum); // 총 페이지 수
return "friend/findFriend";
}
// 내 친구목록 페이지
@GetMapping("/all")
public String allFriendPage(HttpServletRequest request) {
User user = (User)session.getAttribute("principal");
int id = user.getUserId();
List<User>onlineFriends = friendService.checkOnlineFriend(id);
List<User>offlineFriends = friendService.checkOfflineFriend(id);
request.setAttribute("onlineList", onlineFriends);
request.setAttribute("offlineList", offlineFriends);
return "friend/myFriendList";
}
// 대기중인 초대 페이지
@GetMapping("/wait")
public String waitFriendPage(HttpServletRequest request) {
User user = (User)session.getAttribute("principal");
int id = user.getUserId();
List<User>waitFriends = friendService.checkWaitFriendList(id);
List<User>sendFriends = friendService.checkSendFriendList(id);
request.setAttribute("waitList", waitFriends);
request.setAttribute("sendList", sendFriends);
return "friend/waitFriendList";
}
// 친구 요청 보내기
@PostMapping("/sendFriend")
public void postMethodName(@RequestParam(name="userId")int user,
@RequestParam(name="friendId")int friend) {
friendService.insertWaitingFriend(user, friend);
}
// 친구 요청 수락
@GetMapping("/accept/{id}")
public void acceptFriend(@PathVariable("id")int id) {
User user = (User)session.getAttribute("principal");
int userId = user.getUserId();
friendService.addFriend(userId, id);
}
// 친구 요청 거절
@GetMapping("refuse/{id}")
public void refuseFriend(@PathVariable("id")int id) {
User user = (User)session.getAttribute("principal");
int userId = user.getUserId();
friendService.removeWaitFriend(id, userId);
}
// 친구 요청 취소
@GetMapping("cancel/{id}")
public void cancelFriend(@PathVariable("id")int id) {
User user = (User)session.getAttribute("principal");
int userId = user.getUserId();
friendService.removeWaitFriend(userId, id);
}
// 친구 삭제
@GetMapping("remove/{id}")
public void removeFriend(@PathVariable("id")int id) {
User user = (User)session.getAttribute("principal");
int userId = user.getUserId();
friendService.removeFriend(userId, id);
}
}
'My Project > Final Project' 카테고리의 다른 글
2024-09-19(알림 기능 - 1) (0) | 2024.09.25 |
---|---|
2024-09-13 (채팅 기록 불러오기,신고 기능) (1) | 2024.09.13 |
2024-09-06(친구 추가 기능, 알람 소켓) (0) | 2024.09.06 |
2024-09-05 (친구 찾기 기능 and 채팅 로그 저장) (1) | 2024.09.05 |
2024-09-04(매칭 시스템구현 -완) (0) | 2024.09.04 |