반응형
1) 네이버검색API
/WEB-INF/views/naver/search.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>네이버검색</title>
</head>
<body>
<select id="type" class="w3-select w3-border">
<option value="blog">블로그</option><option value="news">뉴스</option>
<option value="book">책</option><option value="encyc">백과사전</option>
<option value="cafeArticle">카페글</option>
<option value="kin">지식인</option><option value="local">지역</option>
<option value="webkr">웹문서</option><option value="image">이미지</option>
<option value="shop">쇼핑</option><option value="doc">전문자료</option>
</select>
페이지 별 검색 갯수 :
<select id="display">
<option>10</option><option>20</option><option>50</option>  
</select>
검색어 : <input type="text" id="data" placeholder="제시어">
<button class="w3-btn w3-blue" onclick="naversearch(1)">검색</button>
<div id="result"></div>
<script>
function naversearch(start){
$.ajax({
type:"POST",
url:"naversearch",
data:{
data:$("#data").val(),
"display" :$("#display").val(),
"start" : start,
"type" : $("#type").val(),
},
success : function(json) {
let total = json.total;
let html = "";
let num = (start-1) * parseInt($("#display").val()) + 1;
let maxpage = Math.ceil(total / parseInt($("#display").val()));
let startpage = (Math.ceil(start/10) - 1) * 10 + 1;
let endpage = startpage + 9;
if(endpage > maxpage) {
endpage = maxpage;
}
html += "<table><tr><td colspan='4' align='center'>" +" 전체 조회 건수 :" +total+", 현재 페이지:"+ start +"/"+maxpage
+"</td></tr>";
$.each(json.items, function(i,item){
html += "<tr><td>"+num+"</td><td>"+item.title+"</td>";
if($("#type").val() === 'image'){
html += "<td><a href='"+item.link+" ' target='_blank'><img src='"+item.thumbnail + "' style='max-width:100px; max-height:100px;'></a></td>";
}
else {
html += "<td><a href ='"+item.link+"' target='_blank'>"+item.link+"</a></td><td>"+item.description+"</td>";
}
html += "</tr>";
num++;
});
html += "<tr><td colspan='4' align='center'>";
if(start > 1) {
html +="<a href='javascript:naversearch("+(start-1)+")'>[이전]</a>";
}
for(let i = startpage; i <= endpage; i++) {
if (i === start) {
html +="<b><a href='javascript:naversearch("+i+")'>["+i+"]</a></b>";
} else {
html +="<a href='javascript:naversearch("+i+")'>["+i+"]</a>";
}
}
if(maxpage > start) {
html +="<a href='javascript:naversearch("+(start+1)+")'>[다음]</a>";
}
html +="</td></tr></table>";
$("#result").html(html);
},
});
}
</script>
</body>
</html>
1-1)클라이언트 코딩
application.properties (gitIgnore처리해놔서 git에 안올라감)
내가올리는 gitRepository가 private가 아니므로 이런비밀암호같은경우는 application에 담아두는것임
자바에서 @Value(${필드명})으로 사용이가능함!!!
naver.secret =나의 secret코드
controller/NaverController
package kr.gdu.controller;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("naver")
public class NaverController {
@Value("${naver.secret}")
private String clientSecret;
@GetMapping("*")
public String naver() {
return null;
}
@PostMapping("naversearch")
@ResponseBody
public JSONObject naversearch(String data, int display , int start , String type) {
String clientId="애플리케이션 클라이언트 아이디값";
clientId = "RzGew7S74e2kohOsbFV7";
StringBuffer json = new StringBuffer();
int cnt = (start-1)*display+1;//네이버에 요청 시작 건수
String text = null;
try {
text = URLEncoder.encode(data,"UTF-8");
String apiURL = "https://openapi.naver.com/v1/search/"
+type+".json?query="+text+"&dispay="+display+"&start="+cnt;
URL url = new URL(apiURL);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("X-Naver-client-Id", clientId);
con.setRequestProperty("X-Naver-client-Secret", clientSecret);
int responseCode = con.getResponseCode();
BufferedReader br;
if(responseCode == 200) {
br = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
}
else {
br = new BufferedReader(new InputStreamReader(con.getErrorStream(),"UTF-8"));
}
String inputLine = null;
while((inputLine=br.readLine())!= null) {
json.append(inputLine);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
JSONParser parser = new JSONParser();
JSONObject jsonObj = null;
try {
jsonObj = (JSONObject)parser.parse(json.toString());
}
catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObj;
}
}
2) 스케쥴링
package kr.gdu.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import kr.gdu.util.CountScheduler;
@Configuration
@EnableScheduling //schedule기능 활성화
/*
* @EnableScheduling은 Spring에서 스케줄링 기능을 활성화하여
* @Scheduled 어노테이션이 붙은 메서드를 주기적으로 실행하도록 설정합니다.
*/
public class BatchConfig {
@Bean
public CountScheduler countScheduler() {
return new CountScheduler();
}
}
config패키지에 다음과같이 BatchConfig라는 spring환경설정 클래스를 만들어둠 @EnableScheduling을 이용해
schdule기능을 활성화 한 상태임!!!
CountScheduler를 한번보자
package kr.gdu.util;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import kr.gdu.service.ShopService;
public class CountScheduler {
@Autowired
private ShopService service;
private int cnt;
/*
@Scheduled(cron="0/5 * * * * ?")
@Scheduled(fixedRate = 5000) //이전작업의 시작시점부터 고정간격
@Scheduled(fixedDelay = 5000) //이전작업의 종료시점부터 고정간격
*/
// 5초마다 실행되는 메서드
//@Scheduled(fixedDelay = 5000)
public void execute1() {
System.out.println("cnt : "+cnt++);
}
//5초 대기 후 3초마다 실행
//@Scheduled(initialDelay=5000 , fixedRate = 3000)
public void execute2() {
System.out.println("5초대기 후 실행");
System.out.println("3초마다실행");
}
/*
* cron
* 1.특정시간 , 주기적으로 프로그램을 실행
* 2.리눅스에서 crontab명령으로 설정 가능
*
* 형식 : 초 분 시 일 월 요일
*
* cron 예시
* 0/10 * * * * ? :10초마다한번씩
* 0 0/1 * * * ? : 1분마다 한번
* 0 20,50 * * * ? : 매 시 20,50분마다 실행
* 0 0 0/3 * * ? : 3시간마다 실행
* 0 0 12 ? * 1 : 월요일12시에실행
* 0 0 12 ? * MON : 월요일12시에실행
* 0 0 10 ? * 6,7 : 주말 10시에 실행
*/
//6월23일 12시20분에 실행해.!
//@Scheduled(cron="0 20 12 23 6 ?")
public void execute3() {
System.out.println("현재시각 : "+new Date());
}
/*
* 1.매일 평일 아침10시30분에 환율(한국수출입은행)을 DB에 저장
*
*
*/
@Scheduled(cron="0 30 10 * * 1,2,3,4,5")
public void exchange() {
service.exchageCreate();
}
}
'Spring' 카테고리의 다른 글
SpringMVC 매개변수 순서의중요성(@Valid , BindingResult, Model) (0) | 2025.06.28 |
---|---|
부트캠프91일차 (new Project JPA,Thymeleaf사용,transaction,Log4j2) (0) | 2025.06.23 |
parameter값 or logic대신 Dto객체 사용 (0) | 2025.06.22 |
Exception과 AOP의 동작원리 (2) | 2025.06.21 |
부트캠프89일차 (chatting) (0) | 2025.06.18 |