최원종의 개발 블로그

V16-4 유료 게시글 구매하기 본문

Spring boot 입문/Spring boot 입문 -1

V16-4 유료 게시글 구매하기

chl6698 2026. 6. 25. 16:29


BoardController 코드 추가⬇️​

// /board/{{board.id}}/purchase
    @PostMapping("/board/{id}/purchase")
    public String purchase(@PathVariable(name = "id") Integer boardId, HttpSession session) {
       User sessionUser = (User) session.getAttribute(Define.SESSION_USER);
        // 포인트 차감
        // 구매 이력 저장
        User updatedUser = purchaseService.구매하기(sessionUser.getId(), boardId);

        // 세션 동기화 처리
        session.setAttribute(Define.SESSION_USER, updatedUser);

        return "redirect:/board/" + boardId;
    }
더보기
@Slf4j
@Controller // IoC
@RequiredArgsConstructor // DI
public class BoardController {

    private final BoardService boardService;
    // 댓글 목록 조회시 필요
    private final ReplyService replyService;
    private final PurchaseService purchaseService;

   
    // /board/{{board.id}}/purchase
    @PostMapping("/board/{id}/purchase")
    public String purchase(@PathVariable(name = "id") Integer boardId, HttpSession session) {
       User sessionUser = (User) session.getAttribute(Define.SESSION_USER);
        // 포인트 차감
        // 구매 이력 저장
        User updatedUser = purchaseService.구매하기(sessionUser.getId(), boardId);

        // 세션 동기화 처리
        session.setAttribute(Define.SESSION_USER, updatedUser);

        return "redirect:/board/" + boardId;
    }
   
    
    // ... 생략 
    }


사용자 예외 클래스 추가

package com.tenco.blog._core.errors;

// 401 NotEnoughException
public class NotEnoughException extends RuntimeException {
    public NotEnoughException(String msg) {
        super(msg);
    }
}

GlobalExceptionHandler

    @ExceptionHandler(NotEnoughException.class)
    @ResponseBody
    public String handleNotEnoughException(NotEnoughException e, HttpServletRequest request) {
        log.warn("=== 포인트 부족 예외 처리 발생 ===");
        log.warn("요청 URL: {}", request.getRequestURL());
        log.warn("에러메시지: {}", e.getMessage());

        String message = e.getMessage() != null ? e.getMessage() : "포인트가 부족합니다";
        String escapeMessage = message.replace("'", "\\'" );
        return """
                <script>
                    alert('%s');
                    location.href='/user/detail'
                </script>
                """.formatted(escapeMessage);
    }

User

//    포인트 관련 편의 메서드 추가
public void deductPoint(Integer amount) {
    if(amount == null || amount <= 0 ) {
        throw new Exception400("차감할 포인트는 0보다 커야 합니다");
    }

    if(this.point < amount) {
        throw new NotEnoughException("포인트가 부족합니다. 현재 포인트 : " + this.point);
    }
    this.point -= amount;
}