ajax - 예제 java 및 Mapper코드 (2022-10-24)

2022. 10. 24. 23:083층 1구역 - 개발의 장/ajax통신

1. 서론

.jsp 예제 파일을 제외한 모든 java 및 Mapper코드 들이다.

 

왜 올리는가?

 

혹시나 모를 오류방지 및 무엇보다 필자가 참고할라고

 

2. 본론

 

ajaxMapper.xml

 

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
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 
<mapper namespace="com.care.ajax.AjaxRepository">
 
    <insert id="insert" parameterType="com.care.ajax.AjaxDTO">
        INSERT INTO ajax VALUES(#{title},#{artist},#{price})
    </insert>
    
    <select id="all" resultType="com.care.ajax.AjaxDTO">
        SELECT * FROM ajax
    </select>
    
    <select id="title" resultType="com.care.ajax.AjaxDTO">
        SELECT * FROM ajax WHERE title LIKE '%'||#{title}||'%'
    </select>
    
    <select id="select" resultType="com.care.ajax.AjaxDTO">
    SELECT * FROM ajax
    <where>
        <if test="sel.equals('title')">
        title like '%'||#{inputData}||'%'
        </if>
        <if test="sel.equals('artist')">
        artist like '%'||#{inputData}||'%'
        </if>
        <if test="sel.equals('price')">
         price like '%'||#{inputData}||'%'
        </if>
    </where>
    </select>
    
 
</mapper>
 
cs

 

AjaxController.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
package com.care.ajax;
 
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
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.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
 
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
 
@Controller
public class AjaxController {
 
//    ex1 Mapping 시작====================================================
    @GetMapping("ex1")
    public String ex1Get() {
        return "ajax/ex1";
    }
 
    // 응답에 리턴값을 담아서 전달하겠다 라는 어노테이션어
    @ResponseBody
    @PostMapping(value = "ex1", produces = "text/html; charset=UTF-8")
    public String ex1Post() {
        return "서버의 응답 데이터";
    }
//    ex1 Mapping 도착====================================================
 
//    ex2 Mapping 시작====================================================
    @GetMapping("ex2")
    public String ex2Get() {
        return "ajax/ex2";
    }
 
    // 클라이언트가 준 데이터를 받는다, 받은 데이터를 클라이언트에게 준다.
    @ResponseBody
    @PostMapping(value = "ex2", produces = "text/html; charset=UTF-8")
    // 바디의 있는 내용을 reqData에 넣어주겠다.
    public String ex2Post(@RequestBody String reqData) {
        return "서버의 응답 데이터 : " + reqData;
    }
//    ex2 Mapping 도착====================================================
 
//    ex3 Mapping 시작====================================================
    @GetMapping("ex3")
    public String ex3Get() {
        return "ajax/ex3";
    }
 
    // 응답에 리턴값을 담아서 전달하겠다 라는 어노테이션어
    @ResponseBody
    @PostMapping(value = "ex3", produces = "application/json; charset=UTF-8")
//    서버에서는 아까 임포트한 jackson databind가 처리해준다.
    public HashMap<StringString> ex3Post(@RequestBody HashMap<StringString> map) {
        System.out.println("아이디 : " + map.get("id"));
        System.out.println("비밀번호 : " + map.get("pw"));
        map.put("id""뭐가 이리"); // value값을 바꿔 잘 넘어가는지 확인해 보기
        map.put("pw""복잡해~!!"); // value값을 바꿔 잘 넘어가는지 확인해 보기
        return map;
    }
//    ex3 Mapping 도착====================================================
 
//    ex4 Mapping 시작====================================================
    @GetMapping("ex4")
    public String ex4Get() {
        return "ajax/ex4";
    }
 
    @ResponseBody
    @PostMapping(value = "ex4", produces = "application/json; charset=UTF-8")
 
    public String ex4Post() throws FileNotFoundException, IOException {
        ClassPathResource resource = new ClassPathResource("ex5.json");
 
//        원래는 File 객체를 생성하면 c드라이브부터 찾아 들어가야 하나(전체경로)
//        ClassPathResource덕분에 src/main/resources 하위부터 읽어올 수 있다
        FileReader reader = new FileReader(resource.getFile());
 
        BufferedReader buffer = new BufferedReader(reader);
 
        String data = "";
 
        while (true) {
//            한줄 씩 읽어와줘 (BufferedReader(buffer).readLine)
            String tmp = buffer.readLine();
            if (tmp == null)
                break;
            data += tmp;
        }
 
        System.out.println(data);
        return data;
    }
//    ex4 Mapping 도착====================================================
 
//    ex5 Mapping 시작====================================================
    @GetMapping("ex5")
    public String ex5Get() {
        return "ajax/ex5";
    }
 
    /*
     * @ResponseBody
     * 
     * @PostMapping(value="ex5", produces = "application/json; charset=UTF-8") //
     * 스플릿으로 하여 배열로 배치하기엔 나는 너무 나약한 사람인가봐... // required = false해주었을 경우 텍스트칸이 비어있다면
     * 결과값이 null이 나온다. 
     * public String ex5Post(@RequestBody(required = false) String title) throws FileNotFoundException, IOException { 
     * ClassPathResource resource = new ClassPathResource("ex5.json"); 
     * FileReader reader = new FileReader(resource.getFile());
     * 
     * Gson gson = new Gson(); 
     * JsonObject obj = gson.fromJson(reader, JsonObject.class);
     * 
     * // System.out.println(data); 
     * System.out.println(obj.toString());
     * System.out.println("title : " + title); 
     * if(title == null) 
     * return obj.toString();
     * 
     * //obj.get("cd") : cd키의 값은 배열(Array) 
     * System.out.println("obj.get(\"cd\") : " + obj.get("cd")); 
     * JsonElement element = obj.get("cd");
     * 
     * JsonArray array = element.getAsJsonArray(); 
     * JsonElement element2 = array.get(0);
     * 
     * // 행 단위 데이터는 { "title" : "Sylvias Mother", "artist" : "Dr.Hook", "price" :
     * "8.10" } JSON 객체 
     * JsonObject obj2 = element2.getAsJsonObject();
     * 
     *getAsString() : 쌍따옴표를 제외한 문자열을 가져온다. 
     *getString() : 쌍따옴표를 포함하여 문자열을 가져온다.
     *
     * System.out.println("obj2.get(\"title\").getAsString() : " + obj2.get("title").getAsString());
     * System.out.println("obj2.get(\"title\").getAsString().equals(title) : " + obj2.get("title").getAsString().equals(title));
     * 
     * 
     * {"cd" : [ { "title" : "Sylvias Mother", "artist" : "Dr.Hook", "price" :
     * "8.10" }, { "title" : "Maggie May", "artist" : "Rod Stewart", "price" :
     * "8.50" } ]} 
     * 아래에서 지금 형식을 만들자.
     * 
     * String data = "{\"cd\" : ["; 
     * boolean check = true; 
     * for(int i = 0; i < array.size(); i++) { 
     * JsonElement e = array.get(i); 
     * JsonObject o = e.getAsJsonObject(); 
     * //getAsString() : 값에서 ""를 제외하고 데이터 추출
     * if(o.get("title").getAsString().equals(title)) { 
     * check = false; 
     * // toString : 값에서 ""를 포함한 데이터 추출 
     * data += "{ \"title\" : " + o.get("title").toString(); 
     * data += ", \"artist\" : "+ o.get("artist").toString(); 
     * data += ", \"price\" :  " + o.get("price").toString() + "},"; } } 
     * // 문자열에서 마지막 문자를 제거(여기서는 콤마(,)) data =
     * data.substring(0, data.length()-1); 
     * data += "]}"; 
     *System.out.println(data);
     * 
     * if(check) 
     * return obj.toString();
     * 
     * return data; 
     * }
     */
 
    
      @ResponseBody
      @PostMapping( value="ex5", produces="application/json; charset=UTF-8"public
      String ex5Post(@RequestBody(required = falseString title) throws FileNotFoundException, IOException { 
        ClassPathResource resource = new
        ClassPathResource("ex5.json"); FileReader reader = new FileReader(resource.getFile());
      
        Gson gson = new Gson(); JsonObject obj = gson.fromJson(reader, JsonObject.class);
      
        if(title == null
          return obj.toString();
      
      JsonArray array = obj.get("cd").getAsJsonArray(); 
      String data = "{\"cd\" : ["
      for(int i = 0; i < array.size(); i++) { 
      JsonObject o = array.get(i).getAsJsonObject();
      if(o.get("title").getAsString().equals(title)) { 
          data += "{ \"title\" : " + o.get("title").toString(); 
          data += ", \"artist\" : "+ o.get("artist").toString(); 
          data += ", \"price\" :  " + o.get("price").toString() + "},"
          } 
      }
      
      data = data.substring(0, data.length()-1); 
      data += "]}";
      
      return data; 
      }
     
 
//    ex5 Mapping 도착====================================================
 
//    ex6 Mapping 시작====================================================
    @Autowired
    AjaxService service;
 
    @ResponseBody
    @GetMapping(value = "ex6Insert", produces = "application/json; charset=UTF-8")
    public String ex6Insert() throws FileNotFoundException, IOException {
        int result = service.insert();
        if (result == 1)
            return "DB 입력 완료";
        return "DB 입력 실패";
    }
 
    @GetMapping("ex6")
    public String ex6Get() {
        return "ajax/ex6";
    }
 
    @ResponseBody
    @PostMapping(value = "ex6", produces = "application/json; charset=UTF-8")
    public String ex6Post(@RequestBody(required = falseString title) {
        if(title == null || title.isEmpty()) {
            return service.all();
        }
        
        return service.title(title);
    }
 
//    ex6 Mapping 도착====================================================
    
//    ex7 Mapping 시작====================================================
    @GetMapping("ex7")
    public String ex7Get() {
        return "ajax/ex7";
    }
    
    @ResponseBody
    @PostMapping(value = "ex7", produces = "application/json; charset=UTF-8")
    public String ex7Post(@RequestBody(required = false) HashMap<StringString> map) {
        
        return service.select(map);
    }
//    ex7 Mapping 도착====================================================
}
cs

 

AjaxDTO.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
package com.care.ajax;
 
/*CREATE TABLE ajax(
  2  title varchar2(20),
  3  artist varchar2(20),
  4  price varchar2(10)
  5  );
Table created.
SQL> commit;
Commit complete.*/
 
public class AjaxDTO {
    private String title;
    private String artist;
    private String price;
    
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getArtist() {
        return artist;
    }
    public void setArtist(String artist) {
        this.artist = artist;
    }
    public String getPrice() {
        return price;
    }
    public void setPrice(String price) {
        this.price = price;
    }
    
    
}
cs

 

AjaxRepository.java

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.care.ajax;
 
import java.util.ArrayList;
import java.util.HashMap;
 
public interface AjaxRepository {
    int insert(AjaxDTO dto);
    
    ArrayList<AjaxDTO> all();
    
    ArrayList<AjaxDTO> title(String title);
    
    ArrayList<AjaxDTO> select(HashMap<StringString> map);
}
cs

 

AjaxService.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
package com.care.ajax;
 
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
 
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
 
@Service
public class AjaxService {
    @Autowired private AjaxRepository repo;
 
    public int insert() throws FileNotFoundException, IOException {
        ClassPathResource resource = new ClassPathResource("ex5.json");
        FileReader reader = new FileReader(resource.getFile());
        
        Gson gson = new Gson();
        JsonObject obj = gson.fromJson(reader, JsonObject.class);
    
        JsonArray array = obj.get("cd").getAsJsonArray(); 
        for(int i = 0; i < array.size(); i++) {
            JsonObject o = array.get(i).getAsJsonObject();
            AjaxDTO dto = new AjaxDTO();
            dto.setTitle(o.get("title").getAsString());
            dto.setArtist(o.get("artist").getAsString());
            dto.setPrice(o.get("price").getAsString());
            
            int result = repo.insert(dto);
            if(result == 0)
                return 0;
        }
        return 1;
    }
    
    public String fromJson(ArrayList<AjaxDTO> list) {
         String data = "{\"cd\" : ["
          for(AjaxDTO tmp : list) { 
              data += "{ \"title\" : \"" + tmp.getTitle() + "\",";
                data +=     " \"artist\" : \"" + tmp.getArtist() + "\",";
                data += " \"price\" : \"" + tmp.getPrice() +"\" },";
          }
          
          data = data.substring(0, data.length()-1); 
          data += "]}";
          
          return data; 
          }
    
    
    public String all()  {
        ArrayList<AjaxDTO> list = repo.all();
        return fromJson(list);
    }
    
    public String title(String title) {
        ArrayList<AjaxDTO> list = repo.title(title);
        return fromJson(list);
    }
    
    public String select(HashMap<StringString> map) {
        ArrayList<AjaxDTO> list = repo.select(map);
        if(list.isEmpty() == true) {
            return "";
        }
        return fromJson(list);
    }
    
}
cs

 

 

DataBaseConfig.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
package com.care.ajax;
 
import java.io.IOException;
 
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
 
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
 
@Configuration
@MapperScan(basePackages = {"com.care.ajax"})
public class DataBaseConfig {
 
    @Bean
    public HikariDataSource dataSource() {
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setDriverClassName("oracle.jdbc.OracleDriver");
        hikariConfig.setJdbcUrl("jdbc:oracle:thin:@localhost:1521:xe");
        hikariConfig.setUsername("oracle");
        hikariConfig.setPassword("oracle");
        
        HikariDataSource dataSource = new HikariDataSource(hikariConfig);
        return dataSource;
    }
    
    @Bean
    public SqlSessionFactoryBean sessionFactory() throws IOException {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        PathMatchingResourcePatternResolver resolver = 
                new PathMatchingResourcePatternResolver();
        Resource[] mapper = resolver.getResources("classpath:/mappers/**/*Mapper.xml");
        sessionFactory.setMapperLocations(mapper);
        return sessionFactory;
                
    }
}
cs

 

3. 결론

 

모아놓고 보니 많이도 했다;;;;