주석 백엔드
This commit is contained in:
@ -14,14 +14,15 @@ import java.util.Arrays;
|
||||
|
||||
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/boards")
|
||||
@RestController //json 형태로 반환
|
||||
@RequestMapping("/boards")// board mapping (get,post 방식으로 url 요청됨)
|
||||
public class BoardController {
|
||||
|
||||
private final BoardService boardService;
|
||||
//유저 삭제시 유저가 작성한 글도 삭제하기 위해 유저 서비스도 참조
|
||||
private final UserService userService;
|
||||
|
||||
@Autowired
|
||||
@Autowired //타입에 해당하는 빈을 찾아줌 -생성자, setter, 필드 Userservice에서 받아옴
|
||||
public BoardController(BoardService boardService, UserService userService) {
|
||||
this.boardService = boardService;
|
||||
this.userService = userService;
|
||||
@ -49,9 +50,10 @@ public class BoardController {
|
||||
@PostMapping("/create")
|
||||
public ResponseEntity<?> createPost(@RequestBody Board board, HttpSession session) {
|
||||
try {
|
||||
// 현재 로그인된 사용자 가져오기
|
||||
// 현재 로그인된 사용자 가져오기 // HTML특정 요소 속성 가져오기
|
||||
User loggedInUser = (User) session.getAttribute("user");
|
||||
if (loggedInUser == null) {
|
||||
//미승인 시 리턴
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("로그인이 필요합니다.");
|
||||
}
|
||||
|
||||
@ -68,7 +70,8 @@ public class BoardController {
|
||||
}
|
||||
}
|
||||
|
||||
// Board 생성 시 로그인된 사용자의 ID를 사용하여 CRT_USER, UDT_USER 설정
|
||||
// Board 게시글 생성 시 로그인된 사용자의 ID를 사용하여 CRT_USER, UDT_USER 설정
|
||||
//로그인 된 유저확인, 게시글 작성시 로그인 유저 정보를 불러와 저장
|
||||
@PostMapping
|
||||
public ResponseEntity<Board> createBoard(@RequestBody Board board, HttpSession session) {
|
||||
String loggedInUser = (String) session.getAttribute("userId");
|
||||
@ -78,6 +81,7 @@ public class BoardController {
|
||||
}
|
||||
|
||||
// Board 수정 시 UDT_USER 업데이트
|
||||
// 게시글 내용 수정시 db에 수정자 변경
|
||||
@PutMapping("/{id}")
|
||||
public ResponseEntity<Board> updateBoard(@PathVariable Long id, @RequestBody Board boardDetails, HttpSession session) {
|
||||
String loggedInUser = (String) session.getAttribute("userId");
|
||||
@ -90,17 +94,17 @@ public class BoardController {
|
||||
@GetMapping("/category/{category}")
|
||||
public List<Board> getBoardsByCategory(
|
||||
@PathVariable("category") String category) {
|
||||
|
||||
//all일때 게시판 테이블 내 데이터 다 가져와서 보여줌
|
||||
if (category.equals("all")) {
|
||||
return boardService.getAllBoards();
|
||||
} else {
|
||||
} else { // 아닐때 카테고리 아이디 받아와서 카테고리 넘버에 맞는 데이터 보여줌
|
||||
int categoryId = getCategoryId(category);
|
||||
return boardService.getBoardsByCategory(categoryId);
|
||||
}
|
||||
}
|
||||
|
||||
// 게시판 나누기
|
||||
private int getCategoryId(String category) {
|
||||
// 게시판 카테고리 분류
|
||||
private int getCategoryId(String category) { //string 카테고리 값을 받아와서 int형으로 바꾸기
|
||||
switch (category) {
|
||||
case "free":
|
||||
return 2;
|
||||
@ -119,7 +123,7 @@ public class BoardController {
|
||||
Board board = boardService.getBoardDetail(boardNumber);
|
||||
return new ResponseEntity<>(board, HttpStatus.OK);
|
||||
}
|
||||
|
||||
//글 수정
|
||||
@PutMapping("/update/{boardNumber}")
|
||||
public ResponseEntity<Board> updateBoard(
|
||||
@PathVariable Long boardNumber,
|
||||
@ -127,11 +131,11 @@ public class BoardController {
|
||||
Board board = boardService.updateBoard(boardNumber, updatedBoard);
|
||||
return new ResponseEntity<>(board, HttpStatus.OK);
|
||||
}
|
||||
|
||||
//글 삭제
|
||||
@DeleteMapping("/delete/{boardNumber}")
|
||||
public ResponseEntity<Void> deleteBoard(@PathVariable Long boardNumber) {
|
||||
boardService.deleteBoard(boardNumber);
|
||||
return new ResponseEntity<>(HttpStatus.NO_CONTENT); // 204 No Content 응답
|
||||
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
}
|
@ -30,12 +30,12 @@ public class UserController {
|
||||
@PostMapping("/register")
|
||||
public ResponseEntity<?> createUser(@RequestBody User user) {
|
||||
try {
|
||||
// 사용자 생성 시 필드 확인
|
||||
// 사용자 생성 시 필드 확인후 메시지 확인
|
||||
if (user.getUserId() == null || user.getUserPassword() == null || user.getUserName() == null) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("필수 필드가 누락되었습니다.");
|
||||
}
|
||||
|
||||
// 새 사용자 생성
|
||||
// 새 사용자 생성 DB에 값 저장
|
||||
user.setCreatedBy("System");
|
||||
user.setUpdatedBy("System");
|
||||
User createdUser = userService.saveUser(user);
|
||||
@ -79,7 +79,7 @@ public class UserController {
|
||||
// 사용자 정보 업데이트 (닉네임, 이름, 비밀번호, 레벨 등)
|
||||
@PutMapping("/{id}")
|
||||
public ResponseEntity<?> updateUserProfile(
|
||||
@PathVariable String id,
|
||||
@PathVariable String id, // 매핑시 중괄호 안에 둘러싸인 값 리소스 식별자 사용 (접속 사용자)
|
||||
@RequestParam("userNickname") String nickname,
|
||||
@RequestParam("userName") String name,
|
||||
@RequestParam("userPassword") String password,
|
||||
@ -103,7 +103,7 @@ public class UserController {
|
||||
}
|
||||
|
||||
|
||||
@PutMapping("/{id}/password")
|
||||
@PutMapping("/{id}/password") //id 값 js에서 받아서 사용
|
||||
public ResponseEntity<?> updatePassword(@PathVariable String id, @RequestBody String newPassword, HttpSession session) {
|
||||
try {
|
||||
// 로그인된 사용자 확인
|
||||
@ -160,10 +160,10 @@ public class UserController {
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("비밀번호 찾기 중 오류 발생: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
//관리자 권한 사용자 업데이트
|
||||
@PutMapping("/admin/{id}")
|
||||
public ResponseEntity<?> updateUser(
|
||||
@PathVariable String id,
|
||||
@PathVariable String id, //id 값으로 불러옴
|
||||
@RequestBody User userDetails) {
|
||||
try {
|
||||
User updatedUser = userService.updateUser(id, userDetails);
|
||||
@ -172,12 +172,12 @@ public class UserController {
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("사용자 업데이트 실패: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
//아이디, 닉네임 중복확인
|
||||
@PostMapping("/check-duplicate")
|
||||
public ResponseEntity<?> checkDuplicate(@RequestBody Map<String, String> requestData) {
|
||||
String userId = requestData.get("userId");
|
||||
String userNickname = requestData.get("userNickname");
|
||||
|
||||
//boolean 으로 true/false 확인
|
||||
boolean isDuplicate = userService.isUserIdOrNicknameExists(userId, userNickname);
|
||||
|
||||
Map<String, Boolean> response = new HashMap<>();
|
||||
|
@ -6,7 +6,7 @@ import java.time.LocalDateTime;
|
||||
@Entity
|
||||
@Table(name = "USER_TB")
|
||||
public class User {
|
||||
|
||||
|
||||
@Id
|
||||
@Column(name = "USER_ID", nullable = false)
|
||||
private String userId;
|
||||
|
@ -1,10 +1,12 @@
|
||||
package com.example.demo.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import com.example.demo.entity.User;
|
||||
|
||||
//CRUD 간편 조작 할 수 있게 만들어줌 findAll(), findById(), save()
|
||||
public interface UserRepository extends JpaRepository<User, String> {
|
||||
//닉네임으로 아이디 찾기
|
||||
User findByUserNickname(String nickname);
|
||||
User findByUserNicknameAndUserId(String nickname, String userId);
|
||||
}
|
||||
//닉네임과 아이디로 비밀번호 찾기
|
||||
User findByUserNicknameAndUserId(String nickname, String userId); //
|
||||
}
|
@ -33,7 +33,7 @@ public class BoardService {
|
||||
}
|
||||
|
||||
// 게시글 저장
|
||||
@Transactional
|
||||
@Transactional // 로그인 되어 있는 사용자 정보 받아서 저장
|
||||
public Board saveBoard(Board board, String loggedInUser) {
|
||||
if (board.getCreatedDate() == null) {
|
||||
board.setCreatedBy(loggedInUser);
|
||||
@ -44,10 +44,10 @@ public class BoardService {
|
||||
|
||||
// 게시글 생성
|
||||
public void createBoard(Board board, User user) {
|
||||
board.setUser(user);
|
||||
board.setCreatedDate(LocalDateTime.now());
|
||||
board.setUser(user); //유저
|
||||
board.setCreatedDate(LocalDateTime.now()); //시간
|
||||
board.setUpdatedDate(LocalDateTime.now());
|
||||
board.setCreatedBy(user.getUserId());
|
||||
board.setCreatedBy(user.getUserId()); //작성자
|
||||
board.setUpdatedBy(user.getUserId());
|
||||
|
||||
boardRepository.save(board);
|
||||
@ -63,11 +63,12 @@ public class BoardService {
|
||||
return boardRepository.findById(boardNumber).orElse(null);
|
||||
}
|
||||
|
||||
// 게시물 상세조회
|
||||
public Board getBoardDetail(Long boardNumber) {
|
||||
return boardRepository.findById(boardNumber)
|
||||
.orElseThrow(() -> new RuntimeException("게시물을 찾을 수 없습니다."));
|
||||
}
|
||||
|
||||
//게시글 수정
|
||||
public Board updateBoard(Long boardNumber, Board updatedBoard) {
|
||||
Board board = boardRepository.findById(boardNumber)
|
||||
.orElseThrow(() -> new RuntimeException("게시물을 찾을 수 없습니다."));
|
||||
@ -76,9 +77,8 @@ public class BoardService {
|
||||
board.setUpdatedDate(LocalDateTime.now());
|
||||
return boardRepository.save(board);
|
||||
}
|
||||
|
||||
//게시글 삭제
|
||||
public void deleteBoard(Long boardNumber) {
|
||||
boardRepository.deleteById(boardNumber);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -93,11 +93,12 @@ public class UserService {
|
||||
User user = userRepository.findByUserNicknameAndUserId(nickname, userId);
|
||||
return user != null ? user.getUserPassword() : null;
|
||||
}
|
||||
|
||||
// 사용자 삭제
|
||||
public void deleteUser(String userId) {
|
||||
userRepository.deleteById(userId);
|
||||
}
|
||||
|
||||
// 관리자 유저 업데이트
|
||||
@Transactional
|
||||
public User updateUser(String id, User userDetails) {
|
||||
Optional<User> userOptional = userRepository.findById(id);
|
||||
@ -113,6 +114,7 @@ public class UserService {
|
||||
}
|
||||
}
|
||||
|
||||
// 유저 아이디 및 닉네임 중복확인
|
||||
public boolean isUserIdOrNicknameExists(String userId, String userNickname) {
|
||||
boolean userIdExists = false;
|
||||
boolean nicknameExists = false;
|
||||
|
Reference in New Issue
Block a user