AI교육과정 - Spring.10

단비·2022년 12월 21일
0

AI교육과정

목록 보기
50/69
  • JAVA에서 HTML에 값 넘기기
    • Controller
      return new ModelAndView("/user_list")
                    .addObject("id", id) // attribute명: id, 값: id값
                    .addObject("name", name);
    • HTML
      • 하기 코드를 통해 tymeleaf 로도 받을 수 있음

        ${id}, ${name}
        <div th:replace="fragment/profile :: profile(${id}, ${name})"></div>
  • 페이징(Paging)
    • DB에 저장된 데이터를 자르는 것
  • Pagination 페이지의 정보
    • getTotalElements()
      • 쿼리 결과물의 전체 데이터 개수. 즉, Pageable에 의해 limit키워드가 조건으로 들어가지 않는 쿼리 결과의 수
    • getTotalPages()
      • 쿼리를 통해 가져온 요소들을 size크기에 맞춰 페이징하였을 때 나오는 총 페이지의 개수
    • getSize()
      • 데이터를 나눠 페이지를 구성할 사이즈
    • getNumber()
      • 요소를 가져온 페이지의 번호
    • getNumberOfElements()
      • 페이지에 존재하는 요소의 개수, 최대 size의 수 만큼 나올 수 있음
  • PageableDefault Controller의 메서드 파라미터에 해당 어노테이션이 선언 된 Pageable 타입 파라미터를 선언하게 되면, API 요청 시 Pageable 객체에 대한 파라미터를 넘겨주지 않아도 자동으로 기본값을 가진 Pageable 타입 파라미터를 제공해줌
    • Controller
      • @PageableDefault(sort={"id"}, direction= Sort.Direction.DESC) Pageable pageable
        - PageableDefault를 이용해 id값을 내림차순으로 정렬한 값을 pageable에 삽입

        @GetMapping("") // http://localhost:8888/api/user?page=1
        public Header<List<UserApiResponse>> findAll(@PageableDefault(size=10, sort={"id"}, direction= Sort.Direction.DESC) Pageable pageable){
            return userApiLogicService.search(pageable);
        }
    • Service
      • Pageable

        JPA에서 제공하는 서비스

        • Pagination
        • Stream.collect()
          Stream의 데이터를 변형 등의 처리를 하고 원하는 자료형으로 변환시켜줌
          • Collectors
            객체들을 자동으로 담아줌

            collect(Collectors.toList() // 객체들을 List형으로 담음
        public Header<List<UserApiResponse>> search(Pageable pageable){
            Page<Users> users = baseRepository.findAll(pageable);
            List<UserApiResponse> userApiResponses = users.stream().map(
                    user -> response(user)).collect(Collectors.toList());
        
            Pagination pagination = Pagination.builder()
                    .totalPages(users.getTotalPages())
                    .totalElements(users.getTotalElements())
                    .currentPage(users.getNumber())
                    .currentElements(users.getNumberOfElements())
                    .build();
                    return Header.OK(userApiResponses, pagination);
        }

  • 클라이언트(프론트엔드) 데이터 처리 방법
    1. fetch
    2. ajax ⇒ jQuery
    3. axios 라이브러리
profile
tistory로 이전! https://sweet-rain-kim.tistory.com/

0개의 댓글