inblog logo
|
code-sudal
    blog

    6. 스프링부트(블로그만들기) 보드 상세보기

    윤주헌's avatar
    윤주헌
    Aug 21, 2024
    6. 스프링부트(블로그만들기) 보드 상세보기
    Contents
    1. 보드 컨트롤러 수정코드PathVariable 왜 사용하냐? 중요@2. 보드 레파지토리 3. 테스트번외 3. 보드 컨트롤러 이동4. detail.mustache가서

    1. 보드 컨트롤러 수정

    notion image
    2번째 에서는 매칭되는 url이 없어..
     
    notion image

    코드

    @GetMapping("/board/{id}") public String detail(@PathVariable("id") Integer id, HttpServletRequest request) { Board board = boardRepository.findById(id); //한건이니까 model //여러건이면 models request.setAttribute("model", board); return "board/detail"; }

    PathVariable 왜 사용하냐? 중요@

    📝
    PathVariable 왜 사용하냐? 중요
    PathVariable 왜 사용하냐? - code-sudal
    java, tip
    PathVariable  왜 사용하냐?  - code-sudal
    https://inblog.ai/code-sudal/pathvariable-왜-사용하냐--28383
    PathVariable  왜 사용하냐?  - code-sudal

    2. 보드 레파지토리

    무조건 DB
     
    DB먼저 테스트 하면 레파지토리쪽은 신경 안 써도 됨
    notion image
    notion image
    조회여서 트랜잭션필요 없음
    //resultset해서 하나씩 파싱해서 받아야 하는데 Board.class 하면 안해도 됨 public Board findById(int id) { Query query = em.createNativeQuery("select * from board_tb where id = ?", Board.class); query.setParameter(1, id); //여러건이 아니니까 single, 빨간줄 뜨는 이유는 다운케스팅만 해주면 됨 Board board = (Board)query.getSingleResult(); return board; }
     

    3. 테스트

    3.1 테스트 코드

    //공장에 기계가 2개 있어 콩 10cm 있다 두번째 10cm 받아서 잘 간다 //첫번째는 10cm이하로 갈리는지확인 //두번째 10cm이하로 갈리는거 확인 할 필요 없음 임의로 갈린다는 것 만 넣으면 된다 이게 기븐 @Test public void findById_test(){ //given int id = 1; //when Board board = boardRepository.findById(id); //eye 사실은 then 원래는 메서드로 해야 하는데 눈으로 해서 (어썰션으로 한다)(통합테스트 할 때 본다) System.out.println(board.getId()); System.out.println(board.getTitle()); System.out.println(board.getContent()); //then Assertions.assertThat(board.getTitle()).isEqualsTo("제목1"); Assertions.assertThat(board.getContent()).isEqualsTo("내용1"); }
    끝 아님

    3.2 경우의 수 생각하기

    만약 6이 없는데 6이 나온다면
    @Test public void findById_test() { //given int id = 6; //when Board board = boardRepository.findById(id); //eye 사실은 then 원래는 메서드로 해야 하는데 눈으로 해서 (어썰션으로 한다)(통합테스트 할 때 본다) System.out.println(board.getId()); System.out.println(board.getTitle()); System.out.println(board.getContent()); }
    오류
    notion image

    3.3 어디서 오류가 나는가?

    여기서 오류남
    notion image
    • 문제 발생
    화면을 누르면 상관 없지만 uri에 숫자 넣으면 문제가 된다 → 예외 잡아야 한다!!
     
    오류 잡자
    //resultset해서 하나씩 파싱해서 받아야 하는데 Board.class 하면 안해도 됨 public Board findById(int id) { Query query = em.createNativeQuery("select * from board_tb where id = ?", Board.class); query.setParameter(1, id); //여러건이 아니니까 single, 빨간줄 뜨는 이유는 다운케스팅만 해주면 됨 try { Board board = (Board) query.getSingleResult(); return board; } catch (Exception e) { return null; } }
    이러면 nullpintException 오류남 → catch되면 null나온다고 했으니까
    notion image
    이거는 DB의 문제인데 테스트를 하지 않는다면 화면의 문제인지 알고 화면만 보고있다
     
     
    • 다른 방법 이제는 예외 내가 제어할 수 있다 → 이거는 버전 2에서 할거다

    3.4 보드 레파지토리에서 예외 제어 표시(임시)

    notion image
    테스트 돌리면 나온다
    notion image
    //resultset해서 하나씩 파싱해서 받아야 하는데 Board.class 하면 안해도 됨 public Board findById(int id) { Query query = em.createNativeQuery("select * from board_tb where id = ?", Board.class); query.setParameter(1, id); //여러건이 아니니까 single, 빨간줄 뜨는 이유는 다운케스팅만 해주면 됨 try { Board board = (Board) query.getSingleResult(); return board; } catch (Exception e) { throw new RuntimeException("게시글 id를 찾을 수 없습니다"); } }
    오류를 알고 있는 상황과 모르는 상황은 다르다 대비가 되는가 안 되는가 중요함!
     
    이제 레파지토리 끝
     

    번외

    C에서 오류났다 try catch해준다 (여기서 오류나면 여기서 해결하겠다)
    throw하면 아씨 나 모르겠는데 다른놈한테 위임함
    만약 A도 throw하면 결국 JVM이 처리함
    notion image
     
    전부 throw로 날려서 최종 부모가 해결하는게 좋다!!
     
    우리가 레이어(디스페치 서블릿 →컨트롤러, → 레파지토리, → em) 많이봄
    지금은 레파지토리에서 에러남 → 모든 것 디스페치 서블릿에서 해결할 수 있게 핸들링 할 수 있게 만듬!!
     
    디스페치 서블릿은 우리가 하는게 아니여서 그냥 던지기만 하면 알아서 해결해준다
     
     

    3. 보드 컨트롤러 이동

    @GetMapping("/board/{id}") public String detail(@PathVariable("id") Integer id, HttpServletRequest request) { Board board = boardRepository.findById(id); //한건이니까 model //여러건이면 models request.setAttribute("model", board); return "board/detail"; }
    • for문 돌리면 {{}} 안에 모델.넣을 필요 없음

    4. detail.mustache가서

    notion image
    {{>layout/header}} <div class="container p-5"> <!-- 수정삭제버튼 --> <div class="d-flex justify-content-end"> <a href="/board/{{model.id}}/update-form" class="btn btn-warning me-1">수정</a> <form action="/board/{{model.id}}/delete" method="post"> <button class="btn btn-danger">삭제</button> </form> </div> <div class="d-flex justify-content-end"> <b>작성자</b> : 익명 </div> <!-- 게시글내용 --> <div> <h2><b>{{model.title}}</b></h2> <hr/> <div class="m-4 p-2"> {{model.content}} </div> </div> </div> {{>layout/footer}}
     
     
    지금은 자바 스크립트 ajax안 쓰고 하려고 post에 insert delete update다 씀 나중에 배울거임
    원래는 주소에 동사 넣지 않는다 하지만
    <form action="/board/{{model.id}}" method="delete"> 원래는 이렇게 사용하면된다
    하지만 4가지 다 쓰려면 js 사용해야 해서 post로 모든 것을 다 사용하기 위해
     
    ajax, js 안 쓰고 java만 사용해서 crud만드려고 함
    Share article

    code-sudal

    RSS·Powered by Inblog