[TOC]
# JSON
## 步驟 1 : 先運行,看到效果,再學習
先將完整的項目(向老師要相關資料),配置運行起來,確認可用之后,再學習做了哪些步驟以達到這樣的效果。
## 步驟 2 : 模仿和排錯
在確保可運行項目能夠正確無誤地運行之后,再嚴格照著教程的步驟,對代碼模仿一遍。
模仿過程難免代碼有出入,導致無法得到期望的運行結果,此時此刻通過比較**正確答案** ( 可運行項目 ) 和自己的代碼,來定位問題所在。
采用這種方式,**學習有效果,排錯有效率**,可以較為明顯地提升學習速度,跨過學習路上的各個檻。
## 步驟 3 : 本知識點效果
本知識點效果有三個,分別是以json方式:提交,獲取單個對象的json結構數據和獲取存儲多個對象的json結構數據。
提交
`http://localhost:8080/ssm/submit.html`
獲取單個
`http://localhost:8080/ssm/getOne.html`
獲取多個
`http://localhost:8080/ssm/getMany.html`
## 步驟 4 : jquery.min.js
因為要使用jquery進行提交和解析json格式數據,所以需要jquery.mini.js復制到WebContent目錄下。

## 步驟 5 : json中文問題
雖然在spring mvc 中文問題里已經提供了過濾器進行ssm的中文處理,但是json處理還要加點額外的內容。
修改springMvc.xml
把原本的
`<mvc:annotation-driven /> `
修改為如下:
~~~
<mvc:annotation-driven >
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/plain;charset=UTF-8" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
~~~
~~~
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- SpringMvc配置文件 -->
<!-- 支持注解 -->
<context:annotation-config />
<!-- 自動掃描包 -->
<context:component-scan base-package="com.dodoke.controller">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- 注解驅動,以使得訪問路徑與方法的匹配可以通過注解配置 -->
<mvc:annotation-driven >
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/plain;charset=UTF-8" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 靜態頁面,如html,css,js,images可以訪問 -->
<mvc:default-servlet-handler />
<!-- 視圖定位到/WEB/INF/jsp 這個目錄下 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
~~~
## 步驟 6 : CategoryController
控制器里提供3個方法,分別用來處理json 提交,json 獲取單個對象,json獲取多個對象
~~~
package com.dodoke.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONObject;
import com.dodoke.pojo.Category;
import com.dodoke.service.CategoryService;
import com.dodoke.util.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
//告訴spring mvc這是一個控制器類
@Controller
@RequestMapping("")
public class CategoryController {
@Autowired
CategoryService categoryService;
@RequestMapping("listCategory")
public ModelAndView listCategory(Page page) {
ModelAndView mav = new ModelAndView();
PageHelper.offsetPage(page.getStart(), 5);
List<Category> cs = categoryService.list();
int total = (int)new PageInfo<>(cs).getTotal();
page.calculateLast(total);
// 放入轉發參數
mav.addObject("cs",cs);
// 放入jsp路徑
mav.setViewName("listCategory");
return mav;
}
@RequestMapping("addCategory")
public ModelAndView addCategory(Category category){
categoryService.add(category);
ModelAndView mav = new ModelAndView("redirect:/listCategory");
return mav;
}
@RequestMapping("deleteCategory")
public ModelAndView deleteCategory(Category category){
categoryService.delete(category);
ModelAndView mav = new ModelAndView("redirect:/listCategory");
return mav;
}
@RequestMapping("editCategory")
public ModelAndView editCategory(Category category){
Category c= categoryService.get(category.getId());
ModelAndView mav = new ModelAndView("editCategory");
mav.addObject("c", c);
return mav;
}
@RequestMapping("updateCategory")
public ModelAndView updateCategory(Category category){
categoryService.update(category);
ModelAndView mav = new ModelAndView("redirect:/listCategory");
return mav;
}
@ResponseBody
@RequestMapping("/submitCategory")
public String submitCategory(@RequestBody Category category) {
System.out.println("SSM接受到瀏覽器提交的json,并轉換為Category對象:"+category);
JSONObject json= new JSONObject();
json.put("key", "ok");
return json.toJSONString();
}
@ResponseBody
@RequestMapping("/getOneCategory")
public String getOneCategory() {
Category c = new Category();
c.setId(100);
c.setName("第100個分類");
JSONObject json= new JSONObject();
json.put("category", JSONObject.toJSON(c));
return json.toJSONString();
}
@ResponseBody
@RequestMapping("/getManyCategory")
public String getManyCategory() {
List<Category> cs = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Category c = new Category();
c.setId(i);
c.setName("分類名稱:"+i);
cs.add(c);
}
return JSONObject.toJSON(cs).toString();
}
}
~~~
> 1. @requestbody 表示獲取請求體中的數據,如 category對象
> 2. @responsetbody 表示該方法的返回的結果直接寫入 HTTP 響應正文(ResponseBody)中,一般在異步獲取數據時使用,通常是在使用 @RequestMapping 后,返回值通常解析為跳轉路徑,加上 @Responsebody 后返回結果不會被解析為跳轉路徑,而是直接寫入HTTP 響應正文中。
## 步驟 7 : submit.html
提交成功后,在tomcat控制臺查看使用json方式提交的數據
注: 不要在eclipse自帶的瀏覽器里面點擊,自帶的瀏覽器有bug,有時候不能識別jquery, 會導致點擊沒有反應。 使用獨立的瀏覽器,比如chrome點擊測試。

~~~
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用AJAX以JSON方式提交數據</title>
</head>
<body>
<form >
id:<input type="text" id="id" value="123" /><br/>
名稱:<input type="text" id="name" value="category xxx"/><br/>
<input type="button" value="提交" id="sender">
</form>
<div id="messageDiv"></div>
</body>
<script type="text/javascript" src="jquery.min.js"></script>
<script>
$('#sender').click(function(){
var id=document.getElementById('id').value;
var name=document.getElementById('name').value;
var category={"name":name,"id":id};
var jsonData = JSON.stringify(category);
var page="submitCategory";
$.ajax({
type:"post",
url: page,
data:jsonData,
dataType:"json",
contentType : "application/json;charset=UTF-8",
success: function(result){
console.log(result);
},
error: function(result) {
console.log(result);
}
});
alert("提交成功,請在Tomcat控制臺查看服務端接收到的數據");
});
</script>
</html>
~~~
> @RequestBody
a) 該注解用于讀取Request請求的body部分數據,根據request的header部分的Content-Type類型,匹配HttpMessageConverter進行解析,然后把相應的數據綁定到要返回的對象上;
b) 再把HttpMessageConverter返回的對象數據綁定到 controller中方法的參數上。
所以`contentType : "application/json;charset=UTF-8",`不能省略。
## 步驟 8 : getOne.html
點擊按鈕,獲取單個對象的json結構數據

~~~
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用AJAX以JSON方式獲取數據</title>
</head>
<body>
<input type="button" value="通過AJAX獲取一個Hero對象" id="sender">
<div id="messageDiv"></div>
</body>
<script type="text/javascript" src="jquery.min.js"></script>
<script>
$('#sender').click(function() {
var url = "getOneCategory";
$.post(url, function(data) {
var json = JSON.parse(data);
var name = json.category.name;
var id = json.category.id;
$("#messageDiv").html("分類id:" + id + "<br>分類名稱:" + name);
});
});
</script>
</html>
~~~
## 步驟 9 : getMany.html
點擊按鈕,獲取存儲多個對象的json結構數據。

~~~
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用AJAX以JSON方式獲取數據</title>
</head>
<body>
<input type="button" value="通過AJAX獲取多個Hero對象111" id="sender">
<div id="messageDiv"></div>
</body>
<script type="text/javascript" src="jquery.min.js"></script>
<script>
$('#sender').click(
function() {
var url = "getManyCategory";
$.post(url, function(data) {
console.log(data);
var categorys = $.parseJSON(data);
console.log(categorys.length);
for (i in categorys) {
var old = $("#messageDiv").html();
var category = categorys[i];
$("#messageDiv").html(old + "<br>" + category.id + " ----- " + category.name);
}
});
}
);
</script>
</html>
~~~
- 數據庫
- 數據庫介紹
- MySQL的安裝
- SQL
- 表基本操作
- 修改數據語句
- 數據檢索操作
- 多表數據操作
- 練習題
- JAVA
- JAVA 介紹
- JAVA 運行原理
- JDK 配置
- 類和對象
- 數據類型
- 變量
- 直接量
- 運算符
- 流程控制
- 數組結構
- 面向對象
- 隱藏和封裝
- 深入構造器
- 類的繼承
- 多態
- 包裝類
- final 修飾符
- 抽象類
- 接口
- 集合框架
- 常用類學習
- 設計模式-單例模式
- 異常處理
- JDBC
- JSP&Servlet
- Web應用
- Tomcat
- JSP
- Scriptlet
- Page 指令
- 包含指令
- 跳轉指令
- 用戶注冊實例
- JSP練習
- 內置對象
- Servlet
- 過濾器
- Web分層思想
- EL表達式
- JSTL
- 分頁實現
- AJAX&JSON
- 開發步驟
- 路徑問題
- Log4j
- Mybatis框架
- 框架介紹
- Mybatis簡單實現
- 表基本操作
- 優化配置文件
- 表字段名與實體類屬性名不同的解決方案
- 一對一關聯
- 一對多關聯
- Spring框架
- IOC/DI
- 注入對象
- 注解方式 IOC/DI
- AOP
- 注解方式AOP
- 注解方式測試
- Spring MVC框架
- Hello SpringMVC
- 視圖定位
- 注解方式
- 接受表單數據
- 客戶端跳轉
- Session
- 中文問題
- 上傳文件
- SSM整合
- 整合步驟
- 分頁
- PageHelper
- 連接池
- CRUD
- 事務管理
- JSON
- Maven
- 介紹
- 下載與配置MAVEN
- MAVEN倉庫
- ECLIPSE中的MAVEN設置
- ECLIPSE下創建MAVEN風格的JAVA項目
- 添加JAR包
- 創建MAVEN風格的JAVA WEB項目
- 創建SSM項目
- 使用ECLIPSE導入一個MAVEN風格的SSM項目
- 教學管理
- 學員名錄
- 周測統計
- 20180608
- 20180706
- 20180721
- 課堂作業
- 練習