관리 메뉴

웹개발자의 기지개

[Spring] Ajax , json 처리 실습2 - DB Pool 이용 본문

Java/Spring

[Spring] Ajax , json 처리 실습2 - DB Pool 이용

http://portfolio.wonpaper.net 2022. 11. 4. 14:14

기존에 실습1이랑 거짐 같으나, DB풀을 이용하여  student테이블의 데이터를 읽어와서  ajax, json 처리하여 보여주는 방식이다.

 

 

jsp spring 프로젝트 전체소스

AjaxTest.zip
0.58MB

 

[ HomeController.java ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package my.control;
 
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.SpringVersion;
 
import java.text.DateFormat;
import java.util.Date;
import java.io.PrintWriter;
import java.io.IOException;
 
import java.util.Locale;
import java.util.ArrayList;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
 
import test.model.StudentDTO;
 
import org.springframework.ui.Model;
import org.apache.commons.dbcp.BasicDataSource;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import java.sql.*;
 
 
@Controller
public class HomeController 
{    
    @Autowired
    BasicDataSource dataSource;
    
    // test/home
    @RequestMapping(value = "/home", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
                
        //hello.method1();
        return "home"// forward : view home.jsp
    }    
 
    // http://localhost:8085/AjaxTest/test/jsoncall    
    @RequestMapping(value = "/jsoncall", method = RequestMethod.GET, produces="application/json;charset=utf8")
    public @ResponseBody String jsoncall(Model model) {        
        // @ResponseBody 는 바로 text 문자로 찍힌다.
                
        //[{"name":"홍길동", "age":20}, {"name":"고길동", "age":22}]
        JSONArray jarr = new JSONArray();        
        
        JSONObject jo1 = new JSONObject();
        jo1.put("name""홍길동");
        jo1.put("age"20);
        
        JSONObject jo2 = new JSONObject();
        jo2.put("name""이순신");
        jo2.put("age"34);        
        
        jarr.add(jo1);
        jarr.add(jo2);
        
        return jarr.toJSONString(); 
    }        
    
    
    // http://localhost:8085/AjaxTest/test/jsoncalldb    
    @RequestMapping(value = "/jsoncalldb", method = RequestMethod.GET, produces="application/json;charset=utf8")
    public @ResponseBody String jsoncalldb(Model model) {        
        // @ResponseBody 는 바로 text 문자로 찍힌다.
                
        //[{"name":"홍길동", "age":20}, {"name":"고길동", "age":22}]
        JSONArray jarr = new JSONArray();
        try{
            String sql ="select * from student";
            Connection conn;
            Statement stmt;
            ResultSet rs;
            conn = dataSource.getConnection();
            stmt = conn.createStatement();  
            rs= stmt.executeQuery(sql); 
            while(rs.next())
            {
                JSONObject jo = new JSONObject();
                
                String name = rs.getString("name");
                int age = rs.getInt("age");
                String birth = rs.getString("birth");
                
                jo.put("name", name);
                jo.put("age", age);
                jo.put("birth", birth);
                jarr.add(jo);
                
            }
            rs.close();
            conn.close();
 
        }catch( Exception ex){
            System.out.println("jsoncalldb(Model model) 에러 : " + ex.getMessage() );
        }        
        
        return jarr.toJSONString(); 
    }            
}
 
 
 
cs

 

jsoncalldb 메소드내용이다.

 

[ ajax.html ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
    h1 {color:red;}
</style>
<script>
    function recvFn() {
        //mydiv.innerText = xhr.responseText; 단순 json문자열로 찍어본다.
        jStr = xhr.responseText
        console.log(jStr)
        
        jArr = JSON.parse(xhr.responseText)
        console.log(jArr)
        
        myh.innerHTML=""
        myb.innerHTML=""
        
        tr = myh.insertRow()
        td1 = tr.insertCell()
        td2 = tr.insertCell()
        td1.innerText = "이름"
        td2.innerText = "나이"
        //<tr><td>이름</td><td>나이</td></tr>
        
        
        for (j of jArr) {
            tr = myb.insertRow()            
            td1 = tr.insertCell()
            td2 = tr.insertCell()
            td1.innerText = j['name']
            td2.innerText = j['age']
        
            console.log(j['name'], j['age'])
        }
    }
    
    function fn() {
        xhr = new XMLHttpRequest();
        xhr.open('GET',"test/jsoncalldb");
        xhr.onload = recvFn; // 수신시 호출되는 함수 등록
        xhr.send();          // ajax요청
    }
</script>
</head>
<body>
    <h1>ajax test</h1>
    <button onclick="fn()">확인</button>
    <a href="test.html" target="myiframe">요청하기</a>
    
    <hr>
    <div id="mydiv"></div>
    
    <table>
        <thead id="myh">
        </thead>    
        <tbody id="myb">
        </tbody>
    </table>
    
    <iframe name="myiframe" width="100%" height="300"></iframe>
</body>
</html>
cs

 

 

 

 

 

 

Comments