본문 바로가기
CLASS/AJAX

#5-5 / Javascript- Ajax 데이터로드(database+인증키 사용)

by hingu 2024. 7. 19.

front에서 버튼 클릭 => database에서 select 로 받아온걸 배열에 담아서  ajax로 전송

⚡ 보안키를 통한 외부 서버에서 data호출(from database)

- ajax4.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<input type="button" value="데이터로드" onclick="ajax()">

<table border="1">
<thead>
	<tr>
		<th>쿠폰명</th>
		<th>할인율</th>
		<th>사용기한</th>
	</tr>
</thead>
<tbody id="dataTable">
	<tr>
		<td colspan="3">쿠폰이 없습니다</td>
	</tr>
</tbody>

</table>
</body>

<script>
	var html = new XMLHttpRequest();
	function ajax(){
		html.onreadystatechange = function(){
			if(html.readyState == 4 && html.status == 200){
				addTable(JSON.parse(this.response));
			}
		}
        
// 		html.open("GET","/jq/rest_ajax4.do",true); //내서버일때

		var keycode = "keycode=a1234"; //보안키가 서로 다를 경우 데이터 받지 못함 
		html.open("GET","http://172.30.1.5:8080/jq/rest_ajax4.do?"+keycode,true);
		html.send();
	}
	
    
    //이건 내가 그냥해보던거..
	function addTable(data){
		var tg = document.getElementById("dataTable");
		
		console.log(data);
// 		var f;
// 		if(data["coupon"].length > 0){
// 			tg.innerHTML = "";
// 			for(f=0; f<data["coupon"].length; f++){
// 				var cpname = data["coupon"][f]["cpname"];
// 				var cprate = data["coupon"][f]["cprate"];
// 				var cpdate = data["coupon"][f]["cpdate"];
				
// 				tg.innerHTML += "<tr><td>"+cpname+"</td><td>"+cprate+"</td><td>"+cpdate+"</td></tr>";
// 			}			
// 		}		
		
	}
</script>
</html>


- @controller 
//javascript ajax Mapping
PreparedStatement ps = null;
ResultSet rs = null;
@CrossOrigin(origins="*", allowedHeaders = "*")
@GetMapping("/jq/rest_ajax4.do")
public String rest_ajax4(String keycode,HttpServletResponse res) throws Exception {
    res.setContentType("text/html;charset=utf-8");

    this.pw = res.getWriter();
    if(keycode==null || keycode == "" || !keycode.equals("a1234")) { //equals만 됨
        this.pw.print("인증키가 확인되지 않습니다");
    }else {
        try {
            Connection con = dbInfo.getConnection();
            String sql = "select * from coupon order by cidx desc";
            this.ps = con.prepareStatement(sql);
            this.rs = this.ps.executeQuery();

            JSONObject jo_rs = new JSONObject();
            JSONArray ja = new JSONArray();
            while(this.rs.next()) {
                JSONObject jo = new JSONObject();
                jo.put("cidx", this.rs.getString(1));
                jo.put("cpname", this.rs.getString(2));
                jo.put("cprate", this.rs.getString(3));
                jo.put("cpuse", this.rs.getString(4));
                jo.put("cpdate", this.rs.getString(5));
                jo.put("indate", this.rs.getString(6));

                ja.add(jo);
            }
            jo_rs.put("coupon", ja); //simple 써서 toString()안해줘도 됩미다

            this.pw.print(jo_rs);

            this.rs.close();
            this.ps.close();
        }catch(Exception e) {
            e.printStackTrace();
            this.pw.print("error");
        }
    }

    return null;
}

https://mindiit.tistory.com/146#toc5 

남의 서버 데이터도 잘 뜸!!! - crossorigin 필수

=> 버튼 클릭하면 table 생성 : 크롤링 못하게 막을수 있다!! 보안 👍