유희를 즐겨
contentId를 가지고 오지 못하거나 api를 가지고 오지 못하는 오류 본문
1)

의 오류가 떴을 때의 코드
/**
* 신고작성
* @return
*/
@PostMapping("/lodgingCheckDetails")
public String lodgingreviewReport(@RequestParam(name = "contentId", required = false) String contentId, UReviewReport reviewReport, HttpServletRequest request) {
log.info("신고 모달 화면에서 입력받은 data: {}", reviewReport);
uReviewService.reviewReport(reviewReport);
return "redirect:/user/destination/lodgingCheckDetails";
}
/**
* 숙소 상제 정보
* @param contentId
* @param model
* @return
* @throws EDException
*/
@GetMapping("/lodgingCheckDetails")
public String lodgingCheckDetails(@RequestParam String contentId, Model model) throws EDException {
StringBuilder result = new StringBuilder();
String serviceKey = "=="; // 실제 서비스 키를 입력하세요
int numOfRows = 100; // 한 페이지당 가져올 항목 수
int startPage = 1; // 시작 페이지 번호
String urlStr = "https://apis.data.go.kr/B551011/KorService1/detailCommon1" +
"?serviceKey=" + serviceKey +
"&MobileOS=ETC" +
"&MobileApp=test" +
"&_type=json" +
"&contentId=" + contentId + // 콘텐츠 ID
"&defaultYN=Y" + // 기본정보 조회 여부
"&firstImageYN=Y" + // 대표이미지 조회 여부
"&areacodeYN=Y" + // 지역코드 조회 여부
"&catcodeYN=Y" + // 서비스분류코드 조회 여부
"&addrinfoYN=Y" + // 주소 조회 여부
"&mapinfoYN=Y" + // 좌표 조회 여부
"&overviewYN=Y"; // 개요 조회 여부
try {
URL url = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
System.out.println("Requesting URL: " + urlStr); // 요청 URL 로그
int responseCode = urlConnection.getResponseCode();
System.out.println("Response Code: " + responseCode); // 응답 코드 로그
if (responseCode == HttpURLConnection.HTTP_OK) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), StandardCharsets.UTF_8))) {
String returnLine;
while ((returnLine = br.readLine()) != null) {
result.append(returnLine).append("\n");
}
}
System.out.println("API Response: " + result.toString()); // API 응답 로그
} else {
throw new EDException("API 요청 실패: 응답 코드 " + responseCode);
}
urlConnection.disconnect();
// JSON 응답을 파싱하여 TourItemResponse 객체로 변환
ObjectMapper mapper = new ObjectMapper();
TourInformationResponse tourInformationResponse = mapper.readValue(result.toString(), TourInformationResponse.class);
System.out.println("Parsed Response: " + tourInformationResponse); // 파싱된 응답 로그
// 모델에 TourItem 리스트 추가
List<TourInformation> tourInformation = tourInformationResponse.getResponse().getBody().getItems().getInformationList();
System.out.println("Tour Information List: " + tourInformation); // TourInformation 리스트 로그
model.addAttribute("TourInformation", tourInformation);
} catch (Exception e) {
e.printStackTrace(); // 예외 스택 트레이스 출력
throw new EDException("Error occurred while calling the API", e);
}
List<UReivewReportCategory> uReviewReportList = uReviewService.getReviewReportCategory();
model.addAttribute("uReviewReportList", uReviewReportList);
// model에 contentId 추가
model.addAttribute("contentId", contentId);
model.addAttribute("title", "숙소 세부사항");
return "user/destination/lodgingCheckDetails";
}
<div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">신고하기</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="reviewReportForm" action="/user/destination/lodgingCheckDetails" method="POST" enctype="multipart/form-data">
<div>
<input type="hidden" id="reviewCodeInput" name="reviewReportReviewCode" readonly>
</div>
<div>
<span class="report-text">신고 리뷰 내용</span>
<textarea class="form-control" id="review-text" disabled></textarea>
</div>
<span>신고자 아이디 : </span>
<input type="text" name="reviewReportUserId" th:value="${session.loginId}" data-review-id="${session.loginId}" readonly />
<div class="btn-group">
<button type="button" class="btn btn-primary dropdown-toggle px-3" data-bs-toggle="dropdown" aria-expanded="false">
신고 유형 선택
</button>
<ul class="dropdown-menu">
<th:block th:each="category : ${uReviewReportList}">
<li>
<a class="dropdown-item" th:text="${category.reviewReportCategoryContent}" th:data-category-code="${category.reviewReportCategoryCode}"></a>
</li>
</th:block>
</ul>
</div>
<input type="hidden" id="reviewReportCategoryCode" name="reviewReportCategoryCode">
<input type="hidden" id="contentId" name="contentId">
<div class="mb-3">
<label for="message-text" class="col-form-label">신고내용:</label>
<textarea class="form-control" id="message-text" maxlength="100" name="reviewReportContent"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">취소</button>
<button type="submit" class="btn btn-primary">신고</button>
</div>
</form>
</div>
</div>
</div>
</div>
$(document).ready(function() {
// 드롭다운 메뉴에서 항목을 클릭할 때 값 할당
$('.dropdown-menu').on('click', '.dropdown-item', function(event) {
// 클릭된 항목의 데이터 속성에서 카테고리 코드를 가져옵니다.
const categoryCode = $(this).data('category-code');
// 콘솔에 categoryCode 값을 출력합니다.
console.log("Selected Category Code:", categoryCode);
// 숨겨진 필드에 해당 값을 할당합니다.
$('#reviewReportCategoryCode').val(categoryCode);
// 버튼 부분에 선택된 값 표시
const selectedText = $(this).text();
$('.dropdown-toggle').text(selectedText);
});
});
이 코드에서 수정하니 아래의 오류가 발생
2)


/**
* 숙소 상제 정보
* @param contentId
* @param model
* @return
* @throws EDException
*/
@GetMapping("/lodgingCheckDetails")
public String lodgingCheckDetails(@RequestParam(name = "contentId", required = false) String contentId, Model model) throws EDException {
StringBuilder result = new StringBuilder();
String serviceKey = "HmjxL3ZwIR9BRISocvJb3ajCyCPzKPzt64QVyJUExpNDFEoSd96yRhkcF6ln23pFPYTSP3v15n23f092lrVAmg=="; // 실제 서비스 키를 입력하세요
int numOfRows = 100; // 한 페이지당 가져올 항목 수
int startPage = 1; // 시작 페이지 번호
String urlStr = "https://apis.data.go.kr/B551011/KorService1/detailCommon1" +
"?serviceKey=" + serviceKey +
"&MobileOS=ETC" +
"&MobileApp=test" +
"&_type=json" +
"&contentId=" + contentId + // 콘텐츠 ID
"&defaultYN=Y" + // 기본정보 조회 여부
"&firstImageYN=Y" + // 대표이미지 조회 여부
"&areacodeYN=Y" + // 지역코드 조회 여부
"&catcodeYN=Y" + // 서비스분류코드 조회 여부
"&addrinfoYN=Y" + // 주소 조회 여부
"&mapinfoYN=Y" + // 좌표 조회 여부
"&overviewYN=Y"; // 개요 조회 여부
try {
URL url = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
System.out.println("Requesting URL: " + urlStr); // 요청 URL 로그
int responseCode = urlConnection.getResponseCode();
System.out.println("Response Code: " + responseCode); // 응답 코드 로그
if (responseCode == HttpURLConnection.HTTP_OK) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), StandardCharsets.UTF_8))) {
String returnLine;
while ((returnLine = br.readLine()) != null) {
result.append(returnLine).append("\n");
}
}
System.out.println("API Response: " + result.toString()); // API 응답 로그
} else {
throw new EDException("API 요청 실패: 응답 코드 " + responseCode);
}
urlConnection.disconnect();
// JSON 응답을 파싱하여 TourItemResponse 객체로 변환
ObjectMapper mapper = new ObjectMapper();
TourInformationResponse tourInformationResponse = mapper.readValue(result.toString(), TourInformationResponse.class);
System.out.println("Parsed Response: " + tourInformationResponse); // 파싱된 응답 로그
// 모델에 TourItem 리스트 추가
List<TourInformation> tourInformation = tourInformationResponse.getResponse().getBody().getItems().getInformationList();
System.out.println("Tour Information List: " + tourInformation); // TourInformation 리스트 로그
model.addAttribute("TourInformation", tourInformation);
} catch (Exception e) {
e.printStackTrace(); // 예외 스택 트레이스 출력
throw new EDException("Error occurred while calling the API", e);
}
List<UReivewReportCategory> uReviewReportList = uReviewService.getReviewReportCategory();
model.addAttribute("uReviewReportList", uReviewReportList);
// model에 contentId 추가
model.addAttribute("contentId", contentId);
model.addAttribute("title", "숙소 세부사항");
return "user/destination/lodgingCheckDetails";
}
컨트롤러는
@RequestParam(name = "contentId", required = false) String contentId 이렇게 수정
<div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">신고하기</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="reviewReportForm" action="/user/destination/lodgingCheckDetails" method="POST" enctype="multipart/form-data">
<div>
<input type="hidden" id="reviewCodeInput" name="reviewReportReviewCode" readonly>
</div>
<div>
<span class="report-text">신고 리뷰 내용</span>
<textarea class="form-control" id="review-text" disabled></textarea>
</div>
<span>신고자 아이디 : </span>
<input type="text" name="reviewReportUserId" th:value="${session.loginId}" data-review-id="${session.loginId}" readonly />
<input type="hidden" id="contentId" name="contentId" th:value="${contentId}">
<div class="btn-group">
<button type="button" class="btn btn-primary dropdown-toggle px-3" data-bs-toggle="dropdown" aria-expanded="false">
신고 유형 선택
</button>
<ul class="dropdown-menu">
<th:block th:each="category : ${uReviewReportList}">
<li>
<a class="dropdown-item" th:text="${category.reviewReportCategoryContent}" th:data-category-code="${category.reviewReportCategoryCode}"></a>
</li>
</th:block>
</ul>
</div>
<input type="hidden" id="reviewReportCategoryCode" name="reviewReportCategoryCode">
<input type="hidden" id="contentId" name="contentId">
<div class="mb-3">
<label for="message-text" class="col-form-label">신고내용:</label>
<textarea class="form-control" id="message-text" maxlength="100" name="reviewReportContent"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">취소</button>
<button type="submit" class="btn btn-primary">신고</button>
</div>
</form>
</div>
</div>
</div>
</div>
<input type="hidden" id="contentId" name="contentId" th:value="${contentId}"> 이 코드 추가
$(document).ready(function() {
// 드롭다운 메뉴에서 항목을 클릭할 때 값 할당
$('.dropdown-menu').on('click', '.dropdown-item', function(event) {
// 클릭된 항목의 데이터 속성에서 카테고리 코드를 가져옵니다.
const categoryCode = $(this).data('category-code');
// contentId를 숨겨진 필드에서 가져옵니다.
const contentId = $('#contentId').val();
console.log("Content ID:", contentId);
// 콘솔에 categoryCode 값을 출력합니다.
console.log("Selected Category Code:", categoryCode);
// 숨겨진 필드에 해당 값을 할당합니다.
$('#reviewReportCategoryCode').val(categoryCode);
// 버튼 부분에 선택된 값 표시
const selectedText = $(this).text();
$('.dropdown-toggle').text(selectedText);
});
});
// contentId를 숨겨진 필드에서 가져옵니다.
const contentId = $('#contentId').val();
console.log("Content ID:", contentId);
이렇게 수정했더니 api로 못받는 문제가 발생
3. 해결