스프링 부트와 Thymeleaf를 이용한 프로젝트를 해보려고 한다.
우선 사용할 API는 TMDB api 이다 .
@Test
public void apiTest() {
RestTemplate rt = new RestTemplate();
ResponseEntity<String> entity = rt.getForEntity("https://api.themoviedb.org/3/tv/popular?language=en-US&page=1&api_key=" + apikey, String.class);
String body = entity.getBody();
System.out.println(body);
}
해당 코드를 돌리면 아래와 같이 값을 정상적으로 받아올 수 있는 것을 알 수 있다.
@Data
public class ApiResponseResult {
private String adult;
private String original_name;
private String overview;
private String popularity;
private String poster_path;
private Date first_air_date;
private String vote_average;
private String vote_count;
}
@ToString
@Getter
public class ApiResponse {
private int page;
private List<ApiResponseResult> results = new ArrayList<>();
private int totalPages;
private int totalResults;
}
Api에서 받아온 정보를 맵핑해준다.
그리고 서비스 계층에서 아래와 같이 코드를 작성해 받아온다.
@Service
public class movieServiceImpl implements movieService {
@Value("${admin}")
private String apikey;
private RestTemplate rt = new RestTemplate();
@Override
public ApiResponse getPopular() {
ResponseEntity<ApiResponse> entity = rt.getForEntity("https://api.themoviedb.org/3/tv/popular?language=en-US&page=1&api_key=" + apikey, ApiResponse.class);
ApiResponse body = entity.getBody();
System.out.println(body);
return body;
}
}
그러면 Controller 단은 아래와 같이 작성한다.
서비스 계층에서 getPopular 메서드를 불러와서 index.html 파일에 불러온 값들을 넘겨준다.
주소가 /v1/popular 이기 떄문에 Postman으로 테스트 해보자
@Controller
public class MainController {
@Autowired
private movieServiceImpl movieService;
@GetMapping("/v1/popular")
public String getPopular(Model model) {
ApiResponse popularMovieList = movieService.getPopular();
model.addAttribute("popularMovieList", popularMovieList);
return "index";
}
}
200 과 함께 아래와 같이 데이터가 정상적으로 반환된 것을 확인할 수 있다 .
사이트에 직접 들어가보면 아래와 같이 나온다.
점차 수정해나가도록 한다.
사진 나오는 부분까지 진행하였다. 아직은 상태가 부실하지만 계속해서 추가해 나가도록 하겠다.
참고 : https://threeyears.tistory.com/42 , https://stockant.tistory.com/564
'자바의 봄(Spring) > 프로젝트' 카테고리의 다른 글
SpringBoot-Movie-Thymeleaf-Project - 4 (0) | 2024.03.20 |
---|---|
SpringBoot-Movie-Thymeleaf-Project - 3 (0) | 2024.03.17 |
공부하면서 만들어가는 REST-API 프로젝트 - 3 (0) | 2024.03.11 |
공부하면서 만들어가는 REST-API 프로젝트 - 2 (0) | 2024.03.09 |
공부하면서 만들어가는 REST-API 프로젝트 (0) | 2024.03.07 |
댓글