본문 바로가기

IT&코딩/Spring

Spring - 9일차 (ajaxConcept)

728x90
반응형

■ AJAX와 JSON

 

AJAX는 Asynchronous JavaScript and XML 의 약자로,

말그대로 JavaScript와 XML을 이용한 비동기적 정보 교환 기법이다.

 

출처 : https://namu.wiki/w/AJAX

 

AJAX - 나무위키

아래의 예제에서는 모두 "//namu.wiki/raw/틀:틀%20모음/" 의 내용을 가져와서 뿌려주는 자바스크립트 코드이다. Ajax 는 비동기 데이터 전송 기술이지만 '양방향' 기술이 아니며 또한 '요청-응답' 사이

namu.wiki

 

JSON은 JavaScript Object Notation의 약자로 

일반적으로 서버에서 클라이언트로 데이터를 보낼 때 사용하는 양식이다.

클라이언트가 사용하는 언어에 관계 없이 통일된 데이터를 주고받을 수 있도록, 일정한 패턴을 지닌 문자열을 생성해 내보내면 클라이언트는 그를 해석해 데이터를 자기만의 방식으로 온전히 저장, 표시할 수 있게 된다.

 

과거 웹 포기 시절부터 사용되어 온 XML은 헤더와 태그 등의 여러 요소로 가독성이 떨어지고, 쓸데없이 용량을 잡아먹는다는 단점이 항상 지적되어 왔다. 이에 대응해 간결하고 통일된 양식으로 각광을 받고 있는 것이 JSON이다.

 

출처 :https://namu.wiki/w/JSON

 

JSON - 나무위키

이 저작물은 CC BY-NC-SA 2.0 KR에 따라 이용할 수 있습니다. (단, 라이선스가 명시된 일부 문서 및 삽화 제외) 기여하신 문서의 저작권은 각 기여자에게 있으며, 각 기여자는 기여하신 부분의 저작권

namu.wiki

 

우선 실습을 위해서는 

 

jackson databind와 GSON 라이브러리가 필요하다.

 

또한 src/main/resources 폴더에 jsonExam.json이라는 json 파일을 추가해준다.

 

□ jsonExam.json

 

{
"cd" : [
{ "title" : "Empire Burlesque", "artist" : "Bob Dylan", "price" : "10.90" },
{ "title" : "Hide your heart", "artist" : "Bonnie Tyler", "price" : "9.90" },
{ "title" : "Greatest Hits", "artist" : "Dolly Parton", "price" : "9.90" },
{ "title" : "Still got the blues", "artist" : "Bob Dylan", "price" : "10.20" },
{ "title" : "Eros", "artist" : "Eros Ramazzotti", "price" : "9.90" },
{ "title" : "One night only", "artist" : "Bee Gees", "price" : "10.90" },
{ "title" : "Sylvias Mother", "artist" : "Dr.Hook", "price" : "8.10" },
{ "title" : "Maggie May", "artist" : "Rod Stewart", "price" : "8.50" },
{ "title" : "Empire Burlesque", "artist" : "Bob Dylan", "price" : "10.90" },
{ "title" : "Hide your heart", "artist" : "Bonnie Tyler", "price" : "9.90" },
{ "title" : "Greatest Hits", "artist" : "Dolly Parton", "price" : "9.90" },
{ "title" : "Still got the blues", "artist" : "Bob Dylan", "price" : "10.20" },
{ "title" : "Eros", "artist" : "Eros Ramazzotti", "price" : "9.90" },
{ "title" : "One night only", "artist" : "Bee Gees", "price" : "10.90" },
{ "title" : "Sylvias Mother", "artist" : "Dr.Hook", "price" : "8.10" },
{ "title" : "Maggie May", "artist" : "Rod Stewart", "price" : "8.50" },
{ "title" : "Empire Burlesque", "artist" : "Bob Dylan", "price" : "10.90" },
{ "title" : "Hide your heart", "artist" : "Bonnie Tyler", "price" : "9.90" },
{ "title" : "Greatest Hits", "artist" : "Dolly Parton", "price" : "9.90" },
{ "title" : "Still got the blues", "artist" : "Bob Dylan", "price" : "10.20" },
{ "title" : "Eros", "artist" : "Eros Ramazzotti", "price" : "9.90" },
{ "title" : "One night only", "artist" : "Bee Gees", "price" : "10.90" },
{ "title" : "Sylvias Mother", "artist" : "Dr.Hook", "price" : "8.10" },
{ "title" : "Maggie May", "artist" : "Rod Stewart", "price" : "8.50" },
{ "title" : "Empire Burlesque", "artist" : "Bob Dylan", "price" : "10.90" },
{ "title" : "Hide your heart", "artist" : "Bonnie Tyler", "price" : "9.90" },
{ "title" : "Greatest Hits", "artist" : "Dolly Parton", "price" : "9.90" },
{ "title" : "Still got the blues", "artist" : "Bob Dylan", "price" : "10.20" },
{ "title" : "Eros", "artist" : "Eros Ramazzotti", "price" : "9.90" },
{ "title" : "One night only", "artist" : "Bee Gees", "price" : "10.90" },
{ "title" : "Sylvias Mother", "artist" : "Dr.Hook", "price" : "8.10" },
{ "title" : "Maggie May", "artist" : "Rod Stewart", "price" : "8.50" },
{ "title" : "Empire Burlesque", "artist" : "Bob Dylan", "price" : "10.90" },
{ "title" : "Hide your heart", "artist" : "Bonnie Tyler", "price" : "9.90" },
{ "title" : "Greatest Hits", "artist" : "Dolly Parton", "price" : "9.90" },
{ "title" : "Still got the blues", "artist" : "Bob Dylan", "price" : "10.20" },
{ "title" : "Eros", "artist" : "Eros Ramazzotti", "price" : "9.90" },
{ "title" : "One night only", "artist" : "Bee Gees", "price" : "10.90" },
{ "title" : "Sylvias Mother", "artist" : "Dr.Hook", "price" : "8.10" },
{ "title" : "Maggie May", "artist" : "Rod Stewart", "price" : "8.50" }
]
}

 


■ com.exam.ajax2 

 

ㅁ AjaxController.java

 

@ResponseBody

@RequestBody

 

클라이언트에서 서버로 필요한 데이터를 요청하기 위해 JSON 데이터를 요청 본문에 담아서 서버로 보내면, 서버에서는 @RequestBody 어노테이션을 사용해 HTTP 요청 본문에 담긴 값들을 자바객체로 변환시켜, 객체에 저장.

 

서버에서는 클라이언트로 응답 데이터를 전송하기 위해 @ResponseBody 를 사용해 자바 객체를 HTTP 응답 본문의 객체로 변환하여 클라이언트로 전송.

 

package com.exam.ajax2;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;

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.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

@Controller
public class AjaxController {
	
	@GetMapping("ex1")
	public String ex1() {
		return "ex1";
	}
	
	@ResponseBody
	/*
	 * @ResponseBody
	 * AJAX 응답 시 사용, JSP를 제공하지 않고, return 데이터를 응답데이터로 사용하겠다 선언
	 * 
	 * produces = "text/html; charset=UTF-8"
	 * 서버의 응답 데이터가 UTF-8이라는 인코딩 데이터라고 웹브라우저에게 알려줌.
	 */
	@PostMapping(value="ex1", produces="text/html; charset=UTF-8")
	public String ex1Post() {
		// return "server response";
		
		return "서버의 응답데이터";
	}
	
	@GetMapping("ex2")
	public void ex2() {}
	
	@PostMapping(value="ex2", produces="text/html; charset=UTF-8")
	public String ex2Post(@RequestBody String sendData) {
		System.out.print("reqData : " + sendData);
		return "서버 응답 데이터 : " + sendData;
	}
	
	@GetMapping("quiz")
	public void quiz() {}
	
	@Autowired private AjaxService service;
	@ResponseBody
	@PostMapping(value="quiz", produces = "text/html; charset=UTF-8")
	public String quizPost(@RequestBody String id) {
		return service.selectId(id);
	}
	
	@GetMapping("ex3")
	public void ex3() {}
	
	@ResponseBody
	@PostMapping(value="ex3", produces = "application/json; charset=UTF-8")
	public Map<String, String> ex3(@RequestBody Map<String, String> map){
		System.out.println("아이디 : " + map.get("id"));
		System.out.println("비밀번호  : " + map.get("pw"));
		
		return map;
	}
	
	@GetMapping("ex4")
	public void ex4() {
		
	}
	
	@ResponseBody
	@PostMapping(value="ex4", produces = "application/json; charset=UTF-8")
	public String ex4Post() {
		ClassPathResource cpResource = new ClassPathResource("jsonExam.json");
		// CLASS_PATH에 저장된 리소스 파일을 쉽게 가져올 수 있도록 해준다.
		
		FileReader reader;
		BufferedReader buffer;
		String data = "";
		
		try {
			reader = new FileReader(cpResource.getFile());
			buffer = new BufferedReader(reader);
			
			while(true) {
				String tmp = buffer.readLine(); // 파일에서 한 줄씩 데이터를 읽어서 반환
				if(tmp == null)
					break;
				data += tmp;
			}
		} catch(FileNotFoundException e) {
			e.printStackTrace();
		} catch(IOException e) {
			e.printStackTrace();
		}
		return data;
	}
	
	@GetMapping("ex5")
	public void ex5() {
		
	}
	
	@ResponseBody
	@PostMapping(value="ex5", produces = "application/json; charset-UTF-8")
	public String ex5Post(@RequestBody(required = false) String title) {
		ClassPathResource cpResource = new ClassPathResource("jsonExam.json");
		
		FileReader reader = null;
		
		try {
			reader = new FileReader(cpResource.getFile());
		} catch(Exception e) {
			
		}
		
		Gson gson = new Gson();
		JsonObject obj = gson.fromJson(reader, JsonObject.class);
		if(title == null)
			return obj.toString();
		
		JsonArray arr = obj.get("cd").getAsJsonArray();
		String data = "{\"cd\" : [";
		for(int i=0; i<arr.size(); i++) {
			JsonObject o = arr.get(i).getAsJsonObject();
			
			if(o.get("title").getAsString().equals(title)) {
				 //System.out.println(o.get("title").getAsString()); Eros
				 //System.out.println(o.get("title").toString()); "Eros"
				data += "{ \"title\" : " + o.get("title").toString() + ",";
				data += " \"artist\" : " + o.get("artist").toString() + ",";
				data += " \"price\" : " + o.get("price").toString();
				data += "},";
			}
		}
		data = data.substring(0, data.length()-1); // 마지막 , 제거
		data += "]}";
		return data;
	}
	
	// 데이터베이스에 값을 넣을 때 해당 맵핑을 이용한다.
	@ResponseBody
	@GetMapping(value = "ex6Insert", produces = "text/html; charset=UTF-8")
	public String insert() {
		service.insert();
		return "데이터베이스에 저장 완료";
	}
	
	@GetMapping("ex6")
	public void ex6() {}
	
	@ResponseBody
	@PostMapping(value="ex6", produces = "application/json; charset=UTF-8")
	public String ex6Post(@RequestBody(required = false) String title) {
		if(title == null || title.isEmpty()) {
			// 모든 데이터
			return service.all();
		}
		// 검색어에 맞는 결과
		return service.title(title);
	}
	
}

 

□ AjaxDTO.java (DTO)

 

package com.exam.ajax2;
/*
CREATE TABLE json(
title varchar2(25),
artist varchar2(16),
price varchar2(6)
);

commit;
 */
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;
}

}

 

□ AjaxRepository.java (DAO 인터페이스)

 

package com.exam.ajax2;

import java.util.ArrayList;

import org.springframework.stereotype.Repository;

@Repository
public interface AjaxRepository {

	public Integer selectId(String id);
	
	public void insert(AjaxDTO ajax);
	
	public ArrayList<AjaxDTO> all();

	public ArrayList<AjaxDTO> title(String title);

}

 

□ AjaxService.java (Service)

 

package com.exam.ajax2;

import java.io.FileReader;
import java.util.ArrayList;

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 repository;
	
	public String selectId(String id) {
		Integer count = repository.selectId(id);
		if(count == 0) {
			return "사용 가능합니다.";
		}else {
			return "이미 사용 중입니다.";
		}
	}
	
	public void insert() {
		ClassPathResource cpResource = new ClassPathResource("jsonExam.json");
		FileReader reader = null;
		try {
			reader = new FileReader(cpResource.getFile());
		} catch (Exception e) {
		}
		
		Gson gson = new Gson();
		JsonObject obj = gson.fromJson(reader, JsonObject.class);
		JsonArray arr = obj.get("cd").getAsJsonArray();
		
		for(int i = 0; i < arr.size(); i++) {
			JsonObject o = arr.get(i).getAsJsonObject();
			
			AjaxDTO ajax = new AjaxDTO();
			ajax.setTitle(o.get("title").getAsString());
			ajax.setArtist(o.get("artist").getAsString());
			ajax.setPrice(o.get("price").getAsString());
			
			repository.insert(ajax);
		}
	}
	public String fromJson(ArrayList<AjaxDTO> list) {
		String data = "{\"cd\" : [";
		if(list.isEmpty()) {
			data += "]}";
			return data;
		}
		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 = repository.all();
		return fromJson(list);
	}

	public String title(String title) {
		ArrayList<AjaxDTO> list = repository.title(title);
		return fromJson(list);
	}

}

 

■ src/main/resources/mappers

 

□ ajaxMapper.xml

 

<?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.exam.ajax2.AjaxRepository">

<select id="selectId" resultType="Integer">
	SELECT count(*) FROM mvc_quiz WHERE id=#{id}
</select>

	<insert id="insert" parameterType="com.exam.ajax2.AjaxDTO">
		INSERT INTO json VALUES(#{title}, #{artist}, #{price} )
	</insert>
	<select id="all" resultType="com.exam.ajax2.AjaxDTO">
		SELECT * FROM json
	</select>

	<select id="title" resultType="com.exam.ajax2.AjaxDTO">
		SELECT * FROM json WHERE title like '%'||#{title}||'%'
	</select>
</mapper>

 

■ root - context.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<bean class="com.zaxxer.hikari.HikariConfig" id="hikariConfig">
		<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
		<property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:xe"/>
		<property name="username" value="spring1212"/>
		<property name="password" value="oracle"/>
	</bean>	
	
	<bean class="com.zaxxer.hikari.HikariDataSource" id="dataSource">
		<constructor-arg ref="hikariConfig"/>
	</bean>
	
	<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sessionFactory">
		<property name="dataSource" ref="dataSource"/>
		<property name="mapperLocations" value="classpath:/mappers/*Mapper.xml" />
	</bean>
	
	<!-- Namespaces tab 에서 mybatis-spring check하고 와서 사용해야함. -->
	<mybatis-spring:scan base-package="com.exam.ajax2"/>
		
</beans>

 

■ view 폴더의 jsp 파일들 (예제)

 

□ ex1

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ex1</title>
<script>
	var req;
	function send(){
		req = new XMLHttpRequest();
		req.onreadystatechange = change;
		req.open('post', 'ex1');
		req.send(null);
	}
	function change(){
		// 200 : ok
		// 404 : not found
		// 500 : server error
		if(req.readyState == 4 && req.status == 200){
			// req.responseText : 서버의 응답데이터
			var print = document.getElementById('print');
			print.innerHTML = req.responseText;
		}
	}
</script>
</head>
<body>
	<div id="print">출력 데이터</div>
	<button type="button" onclick="send()">데이터 가져오기</button>
</body>
</html>

 

<XMLHttpRequest 객체>

서버와 상호작용할 때 사용한다. 페이지의 새로고침 없이도 URL에서 데이터를 가져올 수 있다.

 

onreadystatechange 프로퍼티 : XMLHttpRequest객체의 readyState 프로퍼티 값이 변할 때마다 자동으로 호출되는 함수를 설정한다. 

 

readyState 프로퍼티 : XMLHttpRequest 객체의 현재 상태를 의미한다.

0 (UNSENT) : XMLHttpRequest  객체가 생성됨.

1 (OPENED) : open() 메소드가 성공적으로 실행됨.

2 (HEADERS_RECEIVED) : 모든 요청에 대한 응답이 도착함.

3 (LOADING) : 요청한 데이터를 처리 중임.

4 (DONE) : 요청한 데이터의 처리가 완료되어 응답할 준비가 완료됨. 

 

status 프로퍼티 : 서버의 문서 상태를 나타낸다.

200은 서버에 문서가 존재하는 상태를 의미한다. 404는 존재하지 않는 상태.

 

innerHTML : html 요소에 접근하여 값을 변경할 때 사용한다.

 

□ ex2

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ex2</title>
<script>
	var req;
	function send(){
		req = new XMLHttpRequest();
		var sendData = document.getElementById('sendData');
		req.onreadystatechange = change;
		req.open('post', 'ex2');
		req.send(sendData.value);
	}
	function change(){
		if(req.readyState == 4 && req.status == 200){
			var print = document.getElementById('print');
			print.innerHTML = req.responseText;
		}
	}
</script>
</head>
<body>
	<input type='text' id="sendData" onchange="send()"/>
	<!-- <button type="button" onclick="send()">전송</button> -->
	<br>
	<span id="print"></span><br>
	
</body>
</html>

 

□ quiz

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>quiz</title>
<script>
	var req;
	function send(){
		req = new XMLHttpRequest();
		var id = document.getElementById('id');
		req.onreadystatechange = change;
		req.open('post', 'quiz');
		req.send(id.value);
	}
	function change(){
		if(req.readyState == 4 && req.status == 200){
			var print = document.getElementById('print');
			print.innerHTML = req.responseText;
		}
	}
</script>
</head>
<body>
	<input type='text' id="id" onchange="send()"/><br>
	<span id="print"></span><br>
</body>
</html>

 

 

□ ex3

 

ex3 에서는 Jackson Databind » 2.14.1 라이브러리가 필요함.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ex3</title>
<script>
	//ex3 에서는 Jackson Databind » 2.14.1 라이브러리가 필요함.
	var req;
	function send(){
		req = new XMLHttpRequest();
		var i = document.getElementById('id').value;
		var p = document.getElementById('pw').value;
		var reqData = {id:i, pw:p} // JSON 자료형
		console.log(reqData)
		// 서버에게 요청에 담아서 데이터를 보낼 시에는 문자열로 변환해서 보내야 함.
		// JSON 자료형의 데이터를 문자열로 형변환
		reqData = JSON.stringify(reqData);
		req.onreadystatechange = change;
		req.open('post', 'ex3');
		req.setRequestHeader('Content-Type', "application/json; charset=UTF-8");
		req.send(reqData); // send에는 하나의 변수만 넣을 수 있다.
	}
	function change(){
		if(req.readyState == 4 && req.status == 200){
			var idprint = document.getElementById('idPrint');
			var pwprint = document.getElementById('pwPrint');
			// 서버가 준 데이터는 문자열 자료형으로 전달됨.
			// 키 : 데이터로 구성된 문자열을 JSON 자료형으로 변환
			var resData = JSON.parse(req.responseText);
			idprint.innerHTML = resData.id;
			pwprint.innerHTML = resData.pw;
		}
	}
</script>
</head>
<body>
	<input type="text" id="id"><br>
	<span id="idPrint"></span><br>
	<input type="password" id="pw"><br>
	<span id="pwPrint"></span>
	<button type="button" onclick="send()">로그인</button>
</body>
</html>

 

XMLHttpRequest.setRequestHeader(header, value)

 

open 뒤, send 전에 호출해야 한다.

 

header : 설정될 값을 가진 헤더의 이름

value : 헤더의 본문(body)에 설정될 값

 

□ ex4

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ex4</title>
<script>
	var req;
	function send(){
		req = new XMLHttpRequest();
		req.onreadystatechange = change;
		req.open('post', 'ex4');
		req.send(null);
	}
	function change(){
		if(req.readyState == 4 && req.status == 200){
			var resData = JSON.parse(req.responseText);
			//console.log(resData);
			//console.log('배열의 길이 : ' + resData.cd.length );
			//console.log('title : ' + resData.cd[0].title);
			//console.log('artist : ' + resData.cd[0].artist);
			//console.log('price : ' + resData.cd[0].price);
			printData = "";
			for(i=0; i<resData.cd.length; i++){
				printData += "<tr><td>" + resData.cd[i].title + "</td>";
				printData += "<td>" + resData.cd[i].artist + "</td>";
				printData += "<td>" + resData.cd[i].price + "</td></tr>";
			}
			var tbody = document.getElementById('tbody')
			tbody.innerHTML = printData;
		}
	}
</script>
</head>
<body>
	<button type="button" onclick="send()">실행</button>
	<table border="1">
		<thead>
			<tr>
				<th>title</th>
				<th>artist</th>
				<th>price</th>
			</tr>
		</thead>
		<tbody id="tbody">
		
		</tbody>
	</table>
</body>
</html>

 

□ ex5

 

- 공백인 상태로 실행버튼을 누르면 전체 데이터가 출력됨

- title에 입력된 내용이 있다면 입력된 값과 정확히 일치하는 제목의 데이터들이 출력된다.

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ex5</title>
<script>
	var req;
	function send(){
		req = new XMLHttpRequest();
		req.onreadystatechange = change;
		var title = document.getElementById('title').value;
		req.open('post', 'ex5');
		req.send(title);
	}
	
	function change(){
		if(req.readyState == 4 && req.status == 200){
			var resData = JSON.parse(req.responseText);
			printData = "";
			for(i=0; i<resData.cd.length; i++){
				printData += "<tr><td>" + resData.cd[i].title + "</td>";
				printData += "<td>" + resData.cd[i].artist + "</td>";
				printData += "<td>" + resData.cd[i].price + "</td></tr>";
			}
			var tbody = document.getElementById('tbody')
			tbody.innerHTML = printData;
		}
	}
</script>
</head>
<body>
	<input type="text" id="title">
	<button type="button" onclick="send()">실행</button>
	<table border=1>
		<thead>
			<tr>
				<th>title</th>
				<th>artist</th>
				<th>price</th>
			</tr>
		</thead>
		<tbody id="tbody">
		
		</tbody>
	</table>
</body>
</html>

 

□ ex6

 

- 공백인 상태에는 전체 데이터가 출력됨

- 글자 입력 시 해당 글자를 포함한 title을 가진 데이터들이 출력

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ex6</title>
<script>
	var req;
	function send(){
		req = new XMLHttpRequest();
		req.onreadystatechange = change;
		var title = document.getElementById('title').value;
		req.open('post', 'ex6');
		req.send(title);
	}
	function change(){
		if(req.readyState == 4 && req.status == 200){
			var resData = JSON.parse(req.responseText);
			printData = "";
			for(i = 0 ; i < resData.cd.length; i++){
				printData += "<tr><td>" + resData.cd[i].title + "</td>";
				printData += "<td>" + resData.cd[i].artist + "</td>";
				printData += "<td>" + resData.cd[i].price + "</td></tr>";
			}
			var tbody = document.getElementById('tbody')
			tbody.innerHTML = printData;
		}
	}
</script>
</head>
<body onload="send()">
	<input type="text" id="title" onkeyup="send()">
	<table border=1>
		<thead>
			<tr>
				<th>title</th>
				<th>artist</th>
				<th>price</th>
			</tr>
		</thead>
		<tbody id="tbody">
		
		</tbody>
	</table>
</body>
</html>

 

■ 설정관련 파일

 

□ web.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>
	
	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
		
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>
			org.springframework.web.filter.CharacterEncodingFilter
		</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>

 

■ pom.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.exam</groupId>
	<artifactId>ajax2</artifactId>
	<name>ajaxConcept2</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.8</java-version>
		<org.springframework-version>5.2.1.RELEASE</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</org.slf4j-version>
	</properties>
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				 </exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
				
		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>	
		
		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
				
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	
		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>   
		
		<!-- https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc8 -->
		<dependency>
			<groupId>com.oracle.database.jdbc</groupId>
			<artifactId>ojdbc8</artifactId>
			<version>21.8.0.0</version>
		</dependency>  
		
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-jdbc</artifactId>
		    <version>${org.springframework-version}</version>
		</dependency>
				
		<!-- https://mvnrepository.com/artifact/com.zaxxer/HikariCP -->
		<dependency>
		    <groupId>com.zaxxer</groupId>
		    <artifactId>HikariCP</artifactId>
		    <version>4.0.3</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis</artifactId>
		    <version>3.5.11</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis-spring</artifactId>
		    <version>2.1.0</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
		<dependency>
    		<groupId>com.fasterxml.jackson.core</groupId>
    		<artifactId>jackson-databind</artifactId>
    		<version>2.14.1</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
		<dependency>
    		<groupId>com.google.code.gson</groupId>
    		<artifactId>gson</artifactId>
    		<version>2.10</version>
		</dependency>
		
	</dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
728x90
반응형