-
(국비교육) 62 - 공공 데이터 포털 이용하기 (공기 + 코로나) + 그래프 만들기(차트) + progress bar(스크롤바) 만들기 + thymeleaf + 개발 토이프로젝트 사이트개발/국비교육 2023. 8. 29. 19:11
■ 공고 내용
■ 공공데이터 포털 이용하기
jsp 도 만들어준다.
신청완료된 자료 클릭
json viewer 를 통해 편리하게 볼 수 있다.
StringBuilder urlBuilder = new StringBuilder("http://apis.data.go.kr/1790387/covid19CurrentStatusKorea/covid19CurrentStatusKoreaJason"); /*URL*/ urlBuilder.append("?" + URLEncoder.encode("serviceKey","UTF-8") + "=서비스키"); /*Service Key*/ URL url = new URL(urlBuilder.toString()); 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()); }
서비스키 부분에 마이페이지에 있는 개인 API 인증키를 복사한다.
응답이 제대로 됐음을 확인할 수 있다.
stringBuilder 은 둘 다 문자열을 다루는 클래스이다.
String: String 클래스의 인스턴스는 한 번 생성되면 변경할 수 없다.
문자열 연산 시 새로운 문자열 객체가 생성되며, 이전 문자열은 가비지 컬렉션의 대상이 된다.
StringBuilder: StringBuilder 클래스는 가변성(mutable)을 가지며,문자열 연산을 수행할 때 기존 객체의 수정 및 재사용을 허용한다.
따라서 문자열 연결 등의 작업이 더 효율적으로 이루어질 수 있습니다.
String: 주로 문자열의 불변성이 중요하거나 변경이 없는 경우에 사용됩니다.
예를 들어 상수 문자열이나 불변한 텍스트 데이터를 표현할 때 사용합니다.
StringBuilder: 동적으로 문자열을 구축하거나 변경해야 할 때 사용됩니다.문자열을 반복적으로 조작하거나 큰 문자열을 처리해야 할 때 효과적입니다.
모델에 값 담아주기.
다음과 같이 값 가져올 수 있다.
script 를 닫는 바디태그 위에다 작성해준다.
querySelector를 통해 클래스를 찾고 그 택스트를 할당하는 것이다.
javascript로 찍는 방법이다.
javascript의 경우 처음부터 오류가 나는 경우 진행되지 않으니 주의하자
해당하는 string 값을 다시 json으로 만들고,그 json을 map으로 다시 넣고
그 값을 모델에 담아준다.
동일하게 값을 뽑아낼 수 있다.
* 요청사항
- java / jsp / javascript / j query / jstl 개념 숙지하기
- - JSP파일은 Java Server Pages의 약자로, 서버측 웹 프로그래밍중 하나이다.
HTML 코드 내에 직접 자바코드를 삽입하여 웹서버에서 동적으로 웹페이지를 생성해주고 웹브라우에게 돌려주는 Server측 언어라고 할수있다.
- JS는 Javascript 파일로 클라이언트측 스크립트 언어이다.
웹 브라우저에서 바로 실행되며, 이는 정적인 웹 문서에 동작을 부여하는 스크립트 언어이다.
클라이언트측 = 사용자의 컴퓨터, 서버측 = 웹페이지를 제공하는 컴퓨터
기능적인 요소들은 다 JS에서 구현하고 JSP에서는 JS 파일을 읽어들여와 호출만 해주는식으로 진행
동작구현의 코드들을 따로 관리할수있어 유지보수에 용이하며, js파일을 여러 JSP 파일에서 재사용 할 수 있다.
https://animal-park.tistory.com/14
https://yozm.wishket.com/magazine/detail/94/
StringBuilder urlBuilder = new StringBuilder("http://apis.data.go.kr/B552584/ArpltnStatsSvc/getMsrstnAcctoRDyrg"); /*URL*/ urlBuilder.append("?" + URLEncoder.encode("serviceKey","UTF-8") + "=서비스키"); /*Service Key*/ urlBuilder.append("&" + URLEncoder.encode("returnType","UTF-8") + "=" + URLEncoder.encode("xml", "UTF-8")); /*xml 또는 json*/ urlBuilder.append("&" + URLEncoder.encode("numOfRows","UTF-8") + "=" + URLEncoder.encode("100", "UTF-8")); /*한 페이지 결과 수*/ urlBuilder.append("&" + URLEncoder.encode("pageNo","UTF-8") + "=" + URLEncoder.encode("1", "UTF-8")); /*페이지번호*/ urlBuilder.append("&" + URLEncoder.encode("inqBginDt","UTF-8") + "=" + URLEncoder.encode("20201001", "UTF-8")); /*조회시작일자*/ urlBuilder.append("&" + URLEncoder.encode("inqEndDt","UTF-8") + "=" + URLEncoder.encode("20201030", "UTF-8")); /*조회종료일자*/ urlBuilder.append("&" + URLEncoder.encode("msrstnName","UTF-8") + "=" + URLEncoder.encode("강남구", "UTF-8")); /*측정소명*/ URL url = new URL(urlBuilder.toString()); 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());
코드 복사 후 던지기 처리한다.
다음과 같이 내역 볼 수 있다.
https://codebeautify.org/xmlviewer
json 으로도 볼 수 있다.
utf-8 필요없는 자료는 해당 내용 삭제시켜주기
■ 차트 그리기
https://developers.google.com/chart?hl=ko
■ progress bar 만들기
progress-bar 를 생성해준다.
z-index 레이어를 나타낸다.
숫자가 높을수록 위로 간다.
따라서 progress-container 가 메뉴보다 먼저 올라간다.
스크롤을 내린 만큼 노란색 표시가 진행된다.
■ 타임리프(thymeleaf)
타임리프는 다음과 th 를 사용하여 쓴다.
성공적으로 불러오기 완료
thymeleaf 는 확장자 html 이다.
타임리프 태그가 먼저 로딩된다.
타임리프 사용을 위해서는 th 를 써야 출력된다.
th는 태그 안에서 써야한다.
th는 해당 내용을 덮어쓴다.
따라서 서버에서 보낸 메시지입니다. 는 뜨지만 출력됩니다. 는 뜨지 않는다.
vs code 에서 열어서 확인 가능하다.
타임리프 기본 태그이다.
암기해야 한다.
[[]] 사용시 th 태그 없이 바로 출력 가능하다.
■ utext 와 text 차이
[[${html}]] 로 찍었을 경우 문자열을 그대로 찍힌다.
utext = 태그가 포함되어 있다면 태그까지도 출력한다.
따라서 utext 로 작성한 글은 글자 스타일도 먹는다.
utext 를 다르게 쓰는 방법이다.
링크는 @ 를 사용한다.
파라미터값은 이전과 다르게 ()에 값을 담아서 쓴다.
만약 여러개일 경우 , 로 구분한다.
EL 태그를 통해서 값 가져오기 가능하다.
변수 선언 후 끊으면 값이 뜨지 않는다.
심지어 여기에 이름이 들어가요도 뜨지 않는다.
따라서 다음과 같이 한 줄로 써야 한다.
bno 가 25와 같지 않기 때문에 true,
15가 20보다 작기 때문에 true 가 뜬다.
위에 if 는 false 이기 때문에 뜨지 않고,
아래 if 는 true 이기 때문에 출력된다.
리스트에 담아주고 해당 값을 모델에 담고 출력해보면 다음과 같이 나온다.
반복문 사용 가능
e는 인덱스 개념이다.
* 요청사항
- 개발계획서 참고하여 작성준비
- 세미 최종정리 : 9/26일까지 제작, 발표준비
- 10월 15일까지 이력서, 자기소개서, 포트폴리오 준비
'개발 > 국비교육' 카테고리의 다른 글