본문 바로가기
Spring/프로젝트 코드 리뷰

Spring 클론코딩 프로젝트 MovieController 랜덤출력

by code2772 2023. 3. 3.

[ 목차 ]

    728x90
    반응형

    ✔ 사전 준비(MovieService)

    // 나라&장르 랜덤출력 하기위한 부분
    @Transactional(readOnly = true)
    public List<MovieDto> searchCri(String genre, String country) {
        //빈 웹툰리스폰스 리스트
        List<MovieDto> result = new ArrayList<>();
        List<MovieDto> result2 = new ArrayList<>(10);
    
        List<Movie> movieList2 = movieRepository.findByMovGenreContainingAndMovCountryContaining(genre, country);
    
        for(Movie m : movieList2){
            double sum = 0;
            int starCount = 0;
            for(Star star : m.getStar()){
                sum += star.getStarPoint();
                starCount = m.getStar().size();
            }
            Double avg = Math.round((sum / starCount) * 10.0) / 10.0;
            result.add(MovieDto.from(m, avg));
        }
    
        return result;
    }

     

    먼저 레포지토리에서 findByMovGenreContainingAndMovCountryContaing을 만들어준다. 

    List<Movie> findByMovGenreContainingAndMovCountryContaining(String genre, String country);
     

    위에 for문은 별점 평균을 메인페이지에서 보여주기 위한 부분이다. 있으면 보여주고 없으면 안보여주기 위해 구성하였다.

     

     

    ✔ 랜덤출력

    @GetMapping(path="/main")
    public String movie(
            ModelMap map,HttpSession session
    ){
        UserSessionDto userSessionDto = (UserSessionDto) session.getAttribute("userSession");
        map.addAttribute("userSession", userSessionDto);
        List<MovieDto> movies = movieService.movies();
        map.addAttribute("movies", movies);
    
        String[] gerneList = {"액션","액션","액션","코미디","코미디","코미디", "드라마","드라마"};
        String[] countryList = {"한국","한국","한국","한국","미국","미국", "미국"};
        String[] runningList = {"나 홀로","아이언","해리포터","나 홀로","아이언","해리포터"};
        Random rand = new Random();
        String randomJerne = gerneList[rand.nextInt(gerneList.length)];
        String randomCountry = countryList[rand.nextInt(countryList.length)];
        String randomRunning = runningList[rand.nextInt(runningList.length)];
    
    
        map.addAttribute("searchTop10Movie", searchService.searchTop10Movie());
        map.addAttribute("movieStar", movieService.movieStar());
        map.addAttribute("randomCountry", randomCountry);
    
        map.addAttribute("randomJerne",randomJerne);
        map.addAttribute("movieDtos", movieService.movieDtos());
        map.addAttribute("movieZero", movieService.movieZero());
        map.addAttribute("movies2", movieService.movies2(randomRunning));
        map.addAttribute("movies3", movieService.movies3());
        map.addAttribute("koreanMovies", movieService.searchCountry("한국"));
        map.addAttribute("americanMovies", movieService.searchCountry("미국"));
        map.addAttribute("dramas", movieService.searchDrama("드라마"));
        map.addAttribute("cris", movieService.searchCri(randomJerne,randomCountry));
    
        Long totalCnt = starService.getTotalCnt();
        map.addAttribute("totalCnt",totalCnt);
        return "movie/movieMain";
    }

    HttpSession session : 로그인 화면을 session으로 확인하기 위해 사용

     

    ✔ 랜덤출력

       String[] gerneList = {"액션","액션","액션","코미디","코미디","코미디", "드라마","드라마"};
        String[] countryList = {"한국","한국","한국","한국","미국","미국", "미국"};
        Random rand = new Random();
          String randomJerne = gerneList[rand.nextInt(gerneList.length)];
        String randomCountry = countryList[rand.nextInt(countryList.length)];

     

     map.addAttribute("cris", movieService.searchCri(randomJerne,randomCountry));

     

    1. String형으로 리스트를 만들었다.

    2. Random 함수를 사용하기

    3. 만들었던 리스트들을 랜덤으로 출력해준다. 

    4. 타임리프로 출력하기

     

    ✔ 타임리프에 출력하기

    <!--범죄/한국 -->
    <attr sel=".movie-table-cri" th:remove="all-but-first" >
        <attr sel=".movie-tr-cri" th:each="cris, i : ${cris}" >
            <attr sel=".movie-title" th:text="${cris.movTitle}"/>
            <attr sel=".movie-img" th:src="${cris.movThumbnail}" />
            <attr sel=".movie-making" th:text="${cris.movMakingDate} + ' ・ ' +  ${cris.movCountry}" />
            <!--                메인페이지 순서 count이용 증가 -->
            <attr sel=".movie-idx" th:text="${i.count}" />
            <!--                메인페이지 평균별점       -->
            <attr sel=".average"
                  th:if="${cris.avg} != 0.0" th:text="'평균 ★ ' + (${cris.avg} != 0 ? ${cris.avg} : _)"/>
            <!--                넷플릭스 아이콘        -->
            <attr sel="div.css-5o7sb2" th:if="${cris.movWatch} != null and ${#strings.contains(cris.movWatch,'aHR0cHM6Ly93YXRjaGEuY29tL3dhd')}"/>
            <!--                왓챠 아이콘 -->
            <attr sel="div.css-oobk33" th:if="${cris.movWatch} != null and ${#strings.contains(cris.movWatch,'aHR0cHM6Ly93d3cubmV0ZmxpeC5jb20vdGl0b')}"/>
        </attr>
    </attr>

     

    ✔ 결과

    #장르#국가 부분이 해당 DB를 통해 랜덤으로 출력하게 된다.

    반응형