https://velog.io/@yu_oolong/Spring-JSTL로-화면에-D-day-보여주기 이 글에서 언급한 토이 프로젝트에서 캘린더를 구현하는데 캘린더에 공휴일을 표시해줄 것인지 말 것인지 토글로 on/off할 수 있도록 한다.
공공 데이터 포털에서 한국천문연구원 특일 정보 오픈 API 활용 신청하기
https://www.data.go.kr/data/15012690/openapi.do
Service - RequestAPI.java
https://minaminaworld.tistory.com/211 코드 사용
public class RequestAPI {
private static String secretKey = "발급받은 서비스키";
public static Map<String, Object> holidayInfoAPI(String year, String month) throws IOException {
StringBuilder urlBuilder = new StringBuilder("http://apis.data.go.kr/B090041/openapi/service/SpcdeInfoService/getHoliDeInfo"); /*URL*/
urlBuilder.append("?" + URLEncoder.encode("serviceKey", "UTF-8") + "=" + secretKey); /*Service Key*/
urlBuilder.append("&" + URLEncoder.encode("pageNo", "UTF-8") + "=" + URLEncoder.encode("1", "UTF-8")); /*페이지번호*/
urlBuilder.append("&" + URLEncoder.encode("numOfRows", "UTF-8") + "=" + URLEncoder.encode("10", "UTF-8")); /*한 페이지 결과 수*/
urlBuilder.append("&" + URLEncoder.encode("solYear", "UTF-8") + "=" + URLEncoder.encode(year, "UTF-8")); /*연 */
urlBuilder.append("&" + URLEncoder.encode("solMonth", "UTF-8") + "=" + URLEncoder.encode(month.length() == 1 ? "0" + month : month, "UTF-8")); /*월*/
urlBuilder.append("&" + URLEncoder.encode("_type", "UTF-8") + "=" + URLEncoder.encode("json", "UTF-8")); /* json으로 요청 */
URL url = new URL(urlBuilder.toString());
System.out.println("요청URL = " + urlBuilder);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-type", "application/json");
System.out.println("Response code: " + conn.getResponseCode());
BufferedReader rd;
if (conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) {
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
// System.out.println(sb.toString());
return string2Map(sb.toString());
}
/**
* Json String을 Hashmap으로 반환
*
* @param json
* @return
*/
public static Map<String, Object> string2Map(String json) {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = null;
try {
map = mapper.readValue(json, Map.class);
System.out.println(map);
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
}
//공휴일 Ajax
@PostMapping("/GetHoliday")
@ResponseBody
public ResponseEntity<ArrayList<HashMap<String, Object>>> holidayInfoApi(String year, String month) {
System.out.println("year = " + year);
System.out.println("month = " + month);
ArrayList<HashMap<String, Object>> responseHolidayArr = new ArrayList<HashMap<String, Object>>();
RequestAPI requestAPI = new RequestAPI();
try {
Map<String, Object> holidayMap = requestAPI.holidayInfoAPI(year, month);
Map<String, Object> response = (Map<String, Object>) holidayMap.get("response");
Map<String, Object> body = (Map<String, Object>) response.get("body");
int totalCount = (int) body.get("totalCount");
if(totalCount <= 0) {
System.out.println("공휴일 없음");
System.out.println("body = " + body);
}
if(totalCount == 1) {
HashMap<String, Object> items = (HashMap<String, Object>) body.get("items");
HashMap<String, Object> item = (HashMap<String, Object>) items.get("item");
responseHolidayArr.add(item);
System.out.println("item = " + item);
}
if(totalCount > 1) {
HashMap<String, Object> items = (HashMap<String, Object>) body.get("items");
ArrayList<HashMap<String, Object>> item = (ArrayList<HashMap<String,Object>>) items.get("item");
for(HashMap<String, Object> itemMap : item) {
System.out.println("itemMap = " + itemMap);
responseHolidayArr.add(itemMap);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return new ResponseEntity<>(responseHolidayArr, HttpStatus.OK);
}
<span>공휴일 자동 표시</span>
<input data-toggle="toggle" id="publicAutoN" type="checkbox">
$(document).ready(function() {
//공휴일 자동 표시
$(document).on("change", "#publicAutoY", function(){
console.log("Y->N");
$("#publicAutoY").removeAttr("checked");
$("#publicAutoY").attr("id", "publicAutoN");
var year = $("#year").text();
var month = $("#month").text();
//Ajax로 전송
$.ajax({
url : './GetHoliday',
data : {
year : year,
month : month
},
type : 'POST',
dataType : 'json',
success : function(result) {
if(result != "") {
//div id가 dateiDay인 것들을 전부 조회하여 dateiDay의 .text()값과 조회해온 공휴일 날짜를 비교하여 일치하면 dateContent에 .append()한다.
for(var i = 1; i <= 31; i++) {
for(var j = 0; j < result.length; j++) {
var dateName = result[j].dateName;
var dateId;
//ex)공휴일이 20231003이면 끝의 한 자리만 잘라내고 20231225면 끝의 두 자리면 잘라낸다.
if(((result[j].locdate).toString()).slice(-2).match("0")) {
dateId = "date" + ((result[j].locdate).toString()).slice(-1);
}
else {
dateId = "date" + ((result[j].locdate).toString()).slice(-2);
}
var dateContentId = dateId + "Content";
var date = ((result[j].locdate).toString()).slice(-1);
if ($("#date" + i + "Day").text() == ((result[j].locdate).toString()).slice(-1) || $("#date" + i + "Day").text() == ((result[j].locdate).toString()).slice(-2)) {
$("#" + dateContentId).empty();
}
}
}
}
}
}); //End Ajax
});
$(document).on("change", "#publicAutoN", function(){
console.log("N->Y");
$("#publicAutoN").attr("checked", "checked");
$("#publicAutoN").attr("id", "publicAutoY");
var year = $("#year").text();
var month = $("#month").text();
//Ajax로 전송
$.ajax({
url : './GetHoliday',
data : {
year : year,
month : month
},
type : 'POST',
dataType : 'json',
success : function(result) {
if(result != "") {
//div id가 dateiDay인 것들을 전부 조회하여 dateiDay의 .text()값과 조회해온 공휴일 날짜를 비교하여 일치하면 dateContent에 .append()한다.
for(var i = 1; i <= 31; i++) {
for(var j = 0; j < result.length; j++) {
var dateName = result[j].dateName;
var dateId;
//ex)공휴일이 20231003이면 끝의 한 자리만 잘라내고 20231225면 끝의 두 자리면 잘라낸다.
if(((result[j].locdate).toString()).slice(-2).match("0")) {
dateId = "date" + ((result[j].locdate).toString()).slice(-1);
}
else {
dateId = "date" + ((result[j].locdate).toString()).slice(-2);
}
var dateContentId = dateId + "Content";
var date = ((result[j].locdate).toString()).slice(-1);
if ($("#date" + i + "Day").text() == ((result[j].locdate).toString()).slice(-1) || $("#date" + i + "Day").text() == ((result[j].locdate).toString()).slice(-2)) {
$("#" + dateId).css("color", "#ff0000");
$("#" + dateContentId).append("<br>");
$("#" + dateContentId).append("<a></a> ");
$("#" + dateContentId).append(dateName).css("color", "#ff0000");
}
}
}
}
}
}); //End Ajax
});
}