---
# System prepended metadata

title: RESTful&AJAX 3/8上課內容
tags: [RESTful&AJAX]

---

# RESTful&AJAX 3/8上課內容
###### tags: `RESTful&AJAX`

# 2 AJAX
![](https://i.imgur.com/Jx7NL0h.png)

# 3 AJAX應用的實例
![](https://i.imgur.com/auSEwta.png)
***
![](https://i.imgur.com/zCjTXGj.png)

# 4 傳統網路應用程式的缺點
![](https://i.imgur.com/DIQ4H2v.png)
* 送出需等待 如果沒回來就毀了
***
## AJAX網路應用程式的作法
![](https://i.imgur.com/a1h2E2R.png)
* 使用者介面
 * **AJAX引擎 AJAX engine**
    * 送出請求 請求回應 

# 70(重要)控制器 Controller
![](https://i.imgur.com/nveRsUQ.png)
![](https://i.imgur.com/uYT4Alo.png)
* 系統名稱 Context Path
![](https://i.imgur.com/UnREMn9.png)
* 一樣的寫法

# 5 同步與非同步請求的差異
![](https://i.imgur.com/ctEjmsR.jpg)
* 滑鼠游標對應顏色
![](https://i.imgur.com/6ct6C5z.png)
![](https://i.imgur.com/MQZ9IGg.png)
* 同步:請求送出去 對應 AJAX engine (較好)
* 非同步:無法偵測動作 (偵測事件來等同步)

# 6 傳送資料的差異
![](https://i.imgur.com/ZtzBhl4.png)
* **HTML+CSS data**
    * 完整網頁
* **xml data**
    * 2005年才推出 
* **json**
    * 2005年推出
* **ajax**
    *  提出請求 接受回應
    *  沒有標籤

# 7 AJAX程式設計
![](https://i.imgur.com/Z4utMX9.png)
***
## XMLHttpRequest物件
* AJAX engine
![](https://i.imgur.com/mTu9i9Z.png)

# 8 學習AJAX程式的要點
![](https://i.imgur.com/KuKISF3.png)
![](https://i.imgur.com/OktVzMG.png)
* 嵌入 標籤給id屬性 網頁片段塞到div

# 9 在DOM物件上綁定事件處理函式
![](https://i.imgur.com/FwMJbBv.png)
***
## 如何送出非同步請求?
![](https://i.imgur.com/7PJ2CMo.png)
![](https://i.imgur.com/fftqwX5.png)

# 10 如何接收並處理伺服器送回之回應?
![](https://i.imgur.com/33um0Pt.png)
***
## Server端程式的修正
![](https://i.imgur.com/prZQcQD.png)

# 11 Spring MVC
![](https://i.imgur.com/F0zqP87.png)
* @ResponseBody:轉成json格式(自動轉)
***
## Servlet/JSP
![](https://i.imgur.com/rusIsza.png)

# 12 ch01
![](https://i.imgur.com/jrhEjr9.png)
***
## Chrome
![](https://i.imgur.com/8I2b9HW.png)

# 14 同步請求的範例
![](https://i.imgur.com/vzPRsWq.png)
***
## 非同步請求的範例
![](https://i.imgur.com/ygcTx7Z.png)

#### ex01 
![](https://i.imgur.com/scZQmgq.png)
![](https://i.imgur.com/DPF6YPC.png)
#### Ex01Controller
```clike=
package ex01;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class Ex01Controller {
	
	@GetMapping("/helloAjax126")
	public String sendRegard() {
		return "Hello World, 大家好, Ajax";
	}
}

```
#### ex01.jsp
![](https://i.imgur.com/Zb8tLPe.png)
![](https://i.imgur.com/9gbkyAh.png)
![](https://i.imgur.com/rFgAi4n.png)
![](https://i.imgur.com/QuJbFIJ.png)
```clike=
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>第一個練習</title>
</head>
<body>
<div align="center">
	<h3>練習一</h3>
	<hr>
	<button id='btn01'>回應為單一個字串</button>
	<button id='btn02'>回應為單一個物件</button>
	<button id='btn03'>回應為多個物件</button>
	<hr>
	<div id='dataArea'>
	
	</div>
</div>
</body>
</html>
```
#### ExerciseFindViewController
![](https://i.imgur.com/zAPdLrF.png)
```clike=
package ex01;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class ExerciseFindViewController {

	
	@GetMapping("/ex01")
	public String ex01() {
		return "ex01/ex01";
	}
}

```
#### index.jsp
![](https://i.imgur.com/fU6imI6.png)
```clike=
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>第一個練習</title>
<script type="text/javascript">
window.onload = function(){
	var btn01 = document.getElementById("btn01");
	var btn02 = document.getElementById("btn02");
	var btn03 = document.getElementById("btn03");
	var dataArea = document.getElementById("dataArea");
	btn01.onclick = function(){
		var xhr = new XMLHttpRequest();
		xhr.open("GET", "<c:url value='/helloAjax126' />" ,true);
		xhr.send();
		xhr.onreadystatechange = function(){
			if(xhr.readyState == 4 && xhr.status == 200){
				dataArea.innerHTML = "<font color='red'>" + xhr.responseText + "</font>";
			}
		}
	}
}
</script>
</head>
<body>
<div align="center">
	<h3>練習一</h3>
	<hr>
	<button id='btn01'>回應為單一個字串</button>
	<button id='btn02'>回應為單一個物件</button>
	<button id='btn03'>回應為多個物件</button>
	<hr>
	<div id='dataArea'>
	
	</div>
</div>
</body>
</html>
```
#### 對應路徑
![](https://i.imgur.com/Qz3XXp0.png)
![](https://i.imgur.com/Xb31jYV.png)
![](https://i.imgur.com/fG86mew.png)

#### jstl
```c<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>```
![](https://i.imgur.com/mxxjPWA.png)
![](https://i.imgur.com/w54Nzeg.png)

#### Ex01Controller
```clike=
package ex01;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class Ex01Controller {
	
	@GetMapping(value = "/helloAjax126", produces = "text/plain; charset=UTF-8")
	public @ResponseBody String sendRegard() {
		return "Hello World, 大家好, Ajax";
	}
}

```
#### 系統根目錄
![](https://i.imgur.com/8PwIxKI.png)


#### ex01.jsp
```clike=
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>第一個練習</title>
<script type="text/javascript">
window.onload = function(){
	var btn01 = document.getElementById("btn01");
	var btn02 = document.getElementById("btn02");
	var btn03 = document.getElementById("btn03");
	var dataArea = document.getElementById("dataArea");
	btn01.onclick = function(){
		var xhr = new XMLHttpRequest();
		xhr.open("GET", "<c:url value='/helloAjax126' />" ,true);
		xhr.send();
		xhr.onreadystatechange = function(){
			if(xhr.readyState == 4 && xhr.status == 200){
				dataArea.innerHTML = "<font color='red'>" + xhr.responseText + "</font>";
			}
		}
	}
	btn02.onclick = function(){
		var xhr = new XMLHttpRequest();
		xhr.open("GET", "<c:url value='/findMemberByPk?pk=1' />" ,true);
		xhr.send();
		xhr.onreadystatechange = function(){
			if(xhr.readyState == 4 && xhr.status == 200){
				dataArea.innerHTML = "<font color='red'>" + xhr.responseText + "</font>";
			}
		}
	}
}
</script>
</head>
<body>
<div align="center">
	<h3>練習一</h3>
	<hr>
	<button id='btn01'>回應為單一個字串</button>
	<button id='btn02'>回應為單一個物件</button>
	<button id='btn03'>回應為多個物件</button>
	<hr>
	<div id='dataArea'>
		&nbsp;
	</div>
	
	<a href="/">回前頁-A NG</a>
	<a href="<c:url value='/' />">回前頁-B</a>
</div>
</body>
</html>
```
#### Ex01Controller
```clike=
package ex01;


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import ch04._02.model.Member;
import ex01.service.MemberService;

@Controller
public class Ex01Controller {
	
	@Autowired //控制反轉,依賴注入
	MemberService memberService;
	
	@GetMapping(value = "/helloAjax126", produces = "text/plain; charset=UTF-8")
	public @ResponseBody String sendRegard() {
		return "Hello World, 大家好, Ajax";
	}
	
	@GetMapping("/findMemberByPk")
	public @ResponseBody Member findMemberByPk(@RequestParam Integer pk) {	
		return memberService.findMemberByPk(pk);
	}
	
	@GetMapping("/findMemberById")
	public @ResponseBody Member findMemberById(@RequestParam String id) {	
		return memberService.findMemberById(id);
	}
	
	@GetMapping("/findAllMembers")
	public @ResponseBody List<Member> findAllMembers() {	
		return memberService.findAllMembers();
	}
}


```
#### (interface) MemberService
![](https://i.imgur.com/VE0omj6.png)
![](https://i.imgur.com/ErfEeyR.png)
```clike=
package ex01.service;

import java.util.List;

import ch04._02.model.Member;

public interface MemberService {
	
	Member findMemberByPk(Integer pk);
	
	Member findMemberById(String id);
	
	List<Member> findAllMembers();
}


```

#### DAO -> repository
![](https://i.imgur.com/MQ3S9rY.png)

#### (interface) MemberRepository
![](https://i.imgur.com/MdkqBXV.png)
```clike=
package ex01.repository;

import java.util.List;

import ch04._02.model.Member;

public interface MemberRepository{
	
	Member findMemberByPk(Integer pk);
	
	Member findMemberById(String id);
	
	List<Member> findAllMembers();
}

```

#### MemberRepositoryImpl
![](https://i.imgur.com/MuQoyL7.png)
![](https://i.imgur.com/75Jz9F5.png)
```clike=
package ex01.repository.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import ch04._02.model.Member;
import ex01.repository.MemberRepository;

public class MemberRepositoryImpl implements MemberRepository {

	@Autowired
	SessionFactory factory;
	
	@Override
	public Member findMemberByPk(Integer pk) {
		Session session = factory.getCurrentSession();
		Member member = session.get(Member.class, pk);
		return member;
	}

	@Override
	public Member findMemberById(String id) {
		Session session = factory.getCurrentSession();
		String hql = "FROM Member m WHERE m.id = :mid";
		Member member = null;
		try {
			//getSingleResult()只針對一筆
			member = (Member)session.createQuery(hql).setParameter("mid", id).getSingleResult();
		} catch (Exception e) {
			;
		}
		return member;
	}

	@Override
	public List<Member> findAllMembers() {
		Session session = factory.getCurrentSession();
		String hql = "FROM Member";
		@SuppressWarnings("unchecked")
		List<Member> members = session.createQuery(hql).getResultList();
		return members;
	}

}


```

### 框架 (口試)
* 特性:比較少程式碼 做比較多事
* 介面,類別 裡面的方法 = api
* 缺點:看腦

#### MemberServiceImpl
![](https://i.imgur.com/NeCE443.png)
```clike=
package ex01.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import ch04._02.model.Member;
import ex01.repository.MemberRepository;
import ex01.service.MemberService;

//啟動spring方法裡的交易功能
@Transactional
@Service("snoopy")
public class MemberServiceImpl implements MemberService {
	
	@Autowired
	MemberRepository memberRepository;

	@Override
	public Member findMemberByPk(Integer pk) {
		return memberRepository.findMemberByPk(pk);
	}

	@Override
	public Member findMemberById(String id) {
		return memberRepository.findMemberById(id);
	}

	@Override
	public List<Member> findAllMembers() {
		return memberRepository.findAllMembers();
	}

}

```
### serviec 用的註釋 @Service
### 原DAO->Repository 註釋 @Repository(倉庫)
#### ex01.jsp
```clike=
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>第一個練習</title>
<script type="text/javascript">
window.onload = function(){
	var btn01 = document.getElementById("btn01");
	var btn02 = document.getElementById("btn02");
	var btn03 = document.getElementById("btn03");
	var dataArea = document.getElementById("dataArea");
	btn01.onclick = function(){
		var xhr = new XMLHttpRequest();
		xhr.open("GET", "<c:url value='/helloAjax126' />" ,true);
		xhr.send();
		xhr.onreadystatechange = function(){
			if(xhr.readyState == 4 && xhr.status == 200){
				dataArea.innerHTML = "<font color='red'>" + xhr.responseText + "</font>";
			}
		}
	}
	btn02.onclick = function(){
		var xhr = new XMLHttpRequest();
		xhr.open("GET", "<c:url value='/findMemberByPk?pk=1' />" ,true);
		xhr.send();
		xhr.onreadystatechange = function(){
			if(xhr.readyState == 4 && xhr.status == 200){
			//這個紅色	
//			dataArea.innerHTML = "<font color='red'>" + xhr.responseText + "</font>";
				displayMember(xhr.responseText);
			}
		}
	}
	btn03.onclick = function(){
		var xhr = new XMLHttpRequest();
		xhr.open("GET", "<c:url value='/findAllMembers'  />" ,true);
		xhr.send();
		xhr.onreadystatechange = function(){
			if(xhr.readyState == 4 && xhr.status == 200){
			//這個紅色	
//			dataArea.innerHTML = "<font color='red'>" + xhr.responseText + "</font>";
				displayAllMember(xhr.responseText);
			}
		}
	}
	
}
function displayMember(text){
	var member = JSON.parse(text);
	var segment = "<table border='1'><tr><th>鍵值</th><th>會員代號</th><th>會員姓名</th><th>餘額</th><th>生日</th></tr>";
	
	segment += "<tr><td>" + member.pk + "</td><td>"+ member.id + "</td><td>" + member.name +"</td><td>" + member.balance +"</td><td>" + member.birthday +"</td></tr>" ; 
	segment += "</table>";
	//表格
	dataArea.innerHTML = segment;
	//windows畫面
	//alert(member.pk + "," + member.id + "," + member.name);
}
function displayAllMember(text){
	//視為陣列
	var members = JSON.parse(text);
	var segment = "<table border='1'><tr><th>鍵值</th><th>會員代號</th><th>會員姓名</th><th>餘額</th><th>生日</th></tr>";
	
	for(i = 0; i < members.length; i++){
		var member = members[i]
	segment += "<tr><td>" + member.pk + "</td><td>"+ member.id + "</td><td>" + member.name +"</td><td>" + member.balance +"</td><td>" + member.birthday +"</td></tr>" ; 
	}
	segment += "</table>";
	dataArea.innerHTML = segment;
}
</script>
</head>
<body>
<div align="center">
	<h3>練習一</h3>
	<hr>
	<button id='btn01'>回應為單一個字串</button>
	<button id='btn02'>回應為單一個物件</button>
	<button id='btn03'>回應為多個物件</button>
	<hr>
	<div id='dataArea'>
		&nbsp;
	</div>
	
	<a href="/">回前頁-A NG</a>
	<a href="<c:url value='/' />">回前頁-B</a>
</div>
</body>
</html>
```
#### MemberDaoImpl_Hibernate
![](https://i.imgur.com/2MwAZAs.png)
![](https://i.imgur.com/XBEVwA5.png)
```clike=
package ch04._02.dao.impl;

import java.sql.SQLException;
import java.util.List;

import javax.naming.NamingException;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ch04._02.dao.MemberDao;
import ch04._02.model.Member;

@Repository
public class MemberDaoImpl_Hibernate implements MemberDao {
	
	@Autowired
	SessionFactory factory;
	
	public MemberDaoImpl_Hibernate() throws NamingException, SQLException { 
	
	}
	@SuppressWarnings("unchecked")
	@Override
	public String checkMemberId(String memberId) {
		String hql = "FROM Member m WHERE m.id = :id";
		String id = ""; 
		
		Session session = factory.getCurrentSession();
		
		List<Member> list = session.createQuery(hql)
								   .setParameter("id", memberId)
								   .getResultList();
		if (!list.isEmpty()) {
			id = list.get(0).getId();
		}
		
		return id;
	}
	@Override
	public int saveMember(Member member) {
		
		String id = checkMemberId(member.getId()); 
		if(id.length() > 0) {
			return -1;
		}
		Session session = factory.getCurrentSession();
		session.save(member);
		return 1;
	}
}

```

* jsp沒有類別 只有物件
* java 有類別 有物件

# 15 常用的HTML事件
![](https://i.imgur.com/vB1EKoF.png)

# 19 javaScript 動態物件
![](https://i.imgur.com/eK0QReb.png)

# 20 javaScript的陣列
![](https://i.imgur.com/eyxu4Bi.png)
