JSON
介紹
JSON (JavaScript Object Notation) 是一種輕量級的數據交換格式。易於人閱讀和編寫。同時也易於機器解析和生成。JSON 採用完全獨立於語言的文本格式,而且很多語言都提供了對 json 的支持(包括 C, C++, C#, Java, JavaScript, Perl, Python 等)。 這樣就使得 JSON 成爲理想的數據交換格式。
json 是一種輕量級的數據交換格式。
輕量級指的是跟 xml 做比較。
數據交換指的是客戶端和服務器之間業務數據的傳遞格式。
JSON 在 JavaScript 中的使用
代碼:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
// json的定義
var jsonObj = {
"key1":12,
"key2":"abc",
"key3":true,
"key4":[11,"arr",false],
"key5":{
"key5_1" : 551,
"key5_2" : "key5_2_value"
},
"key6":[{
"key6_1_1":6611,
"key6_1_2":"key6_1_2_value"
},{
"key6_2_1":6621,
"key6_2_2":"key6_2_2_value"
}]
};
alert(typeof(jsonObj));// object json就是一個對象
// alert(jsonObj.key1); //12
// alert(jsonObj.key2); // abc
// alert(jsonObj.key3); // true
// alert(jsonObj.key4);// 得到數組[11,"arr",false]
// // json 中 數組值的遍歷
// for(var i = 0; i < jsonObj.key4.length; i++) {
// alert(jsonObj.key4[i]);
// }
// alert(jsonObj.key5.key5_1);//551
// alert(jsonObj.key5.key5_2);//key5_2_value
// alert( jsonObj.key6 );// 得到json數組
//
// // 取出來每一個元素都是json對象
// var jsonItem = jsonObj.key6[0];
// // alert( jsonItem.key6_1_1 ); //6611
// alert( jsonItem.key6_1_2 ); //key6_1_2_value
// alert(jsonObj);
// 把json對象轉換成爲 json字符串
var jsonObjString = JSON.stringify(jsonObj); // 特別像 Java中對象的toString
alert(jsonObjString)
// 把json字符串。轉換成爲json對象
var jsonObj2 = JSON.parse(jsonObjString);
alert(jsonObj2.key1);// 12
alert(jsonObj2.key2);// abc
// json的訪問
// json對象轉字符串
// json字符串轉json對象
</script>
</head>
<body>
</body>
</html>
json 的定義
json 是由鍵值對組成,並且由花括號(大括號)包圍。每個鍵由引號引起來,鍵和值之間使用冒號進行分隔, 多組鍵值對之間進行逗號進行分隔。
json 的訪問
json 本身是一個對象。 .
json 中的 key 我們可以理解爲是對象中的一個屬性。
json 中的 key 訪問就跟訪問對象的屬性一樣: json 對象.key
json 的兩個常用方法
json 的存在有兩種形式。
一種是:對象的形式存在,我們叫它 json 對象。
一種是:字符串的形式存在,我們叫它 json 字符串。
一般我們要操作 json 中的數據的時候,需要 json 對象的格式。
一般我們要在客戶端和服務器之間進行數據交換的時候,使用 json 字符串。
JSON.stringify() 把 json 對象轉換成爲 json 字符串
JSON.parse() 把 json 字符串轉換成爲 json 對象
JSON 在 java 中的使用
javaBean 和 json 的互轉
javaBean類:
package you;
public class Student {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "id:"+id+" name:"+name;
}
}
測試javaBean;
package you;
import org.junit.Test;
import com.google.gson.Gson;
public class test {
@Test
public void test1(){
Student s=new Student(1,"name");
// 創建 Gson 對象實例
Gson gson = new Gson();
// toJson 方法可以把 java 對象轉換成爲 json 字符串
String personJsonString = gson.toJson(s);
System.out.println(personJsonString);
// fromJson 把 json 字符串轉換回 Java 對象
// 第一個參數是 json 字符串
// 第二個參數是轉換回去的 Java 對象類型
s = gson.fromJson(personJsonString, Student.class);
System.out.println(s); }
}
List 和 json 的互轉
StudentType類
import java.util.ArrayList;
import com.google.gson.reflect.TypeToken;
public class StudentType extends TypeToken<ArrayList<Student>> {
}
測試方法
根據前面的javaBean 和 json 的互轉改換
@Test
public void test2() {
List<Student> personList = new ArrayList<Student>();
personList.add(new Student(1, "name1"));
personList.add(new Student(2, "name2"));
Gson gson = new Gson();
// 把 List 轉換爲 json 字符串
String personListJsonString = gson.toJson(personList);
System.out.println(personListJsonString);
List<Student> list = gson.fromJson(personListJsonString, new StudentType().getType());
System.out.println(list);
Student person = list.get(0);
System.out.println(person); }
map 和 json 的互轉
StudentType
import java.util.ArrayList;
import java.util.Map;
import com.google.gson.reflect.TypeToken;
public class StudentType extends TypeToken<Map<Integer,Student>> {
}
test
根據前面的javaBean 和 json 的互轉改換
@Test
public void test3(){
Map<Integer,Student> personMap = new HashMap<Integer,Student>();
personMap.put(1, new Student(1, "name1"));
personMap.put(2, new Student(2, "name2"));
Gson gson = new Gson();
// 把 map 集合轉換成爲 json 字符串
String personMapJsonString = gson.toJson(personMap);
System.out.println(personMapJsonString);
Map<Integer,Student> personMap2 = gson.fromJson(personMapJsonString, new StudentType().getType());
//第二種匿名內部類,這樣不用寫StudentType類
//Map<Integer,Student> personMap2 = gson.fromJson(personMapJsonString, new TypeToken<HashMap<Integer,Student>>(){}.getType());
System.out.println(personMap2);
Student p = personMap2.get(1);
System.out.println(p); }
AJAX 請求
介紹
AJAX 即“Asynchronous Javascript And XML”(異步 JavaScript 和 XML),是指一種創建交互式網頁應用的網頁開發 技術。
ajax 是一種瀏覽器通過 js 異步發起請求,局部更新頁面的技術。 Ajax 請求的局部更新,瀏覽器地址欄不會發生變化 局部更新不會捨棄原來頁面的內容
Student
public class Student {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "id:"+id+" name:"+name;
}
}
BaseServlet
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import java.io.IOException;
import java.lang.reflect.Method;
public class BaseServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("please");
Student s=new Student(1,"name1");
Gson gson=new Gson();
String v=gson.toJson(s);
resp.getWriter().write(v);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
ajax.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
// 在這裏使用javaScript語言發起Ajax請求,訪問服務器AjaxServlet中javaScriptAjax
function ajaxRequest() {
// 1、我們首先要創建XMLHttpRequest
var xmlhttprequest = new XMLHttpRequest();
// 2、調用open方法設置請求參數
xmlhttprequest.open("GET","http://pc202004141500:8080/web3/BaseServlet?action=dog",true);
// 4、在send方法前綁定onreadystatechange事件,處理請求完成後的操作。
xmlhttprequest.onreadystatechange = function(){
if (xmlhttprequest.readyState == 4 && xmlhttprequest.status == 200) {
// alert("收到服務器返回的數據:" + xmlhttprequest.responseText);
var jsonObj = JSON.parse(xmlhttprequest.responseText);
// 把響應的數據顯示在頁面上
document.getElementById("div01").innerHTML = "編號:" + jsonObj.id + " , 姓名:" + jsonObj.name;
}
}
// 3、調用send方法發送請求
xmlhttprequest.send();
alert("我是最後一行的代碼");
}
</script>
</head>
<body>
<button onclick="ajaxRequest()">ajax request</button>
<div id="div01">
</div>
</body>
</html>
jQuery 中的 AJAX 請求
$.ajax 方法
url 表示請求的地址
type 表示請求的類型 GET 或 POST 請求
data 表示發送給服務器的數據 格式有兩種:
一:name=value&name=value
二:{key:value}
success 請求成功,響應的回調函數
dataType 響應的數據類型 常用的數據類型有: text 表示純文本 xml 表示 xml 數據 json 表示 json 對象
用到前面的student類和Baseservlet類
例子:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
// ajax請求
$("#ajaxBtn").click(function(){
$.ajax({
url:"http://pc202004141500:8080/web3/BaseServlet",
// data:"action=jQueryAjax",這兩種都可以
data:{action:"doGet"},
type:"GET",
success:function (data) {
alert("服務器返回的數據是:" + data);
var jsonObj = JSON.parse(data);
$("#msg").html(" ajax 編號:" + jsonObj.id + " , 姓名:" + jsonObj.name);
},
dataType : "text"//如果是json,success方法換成$("#msg").html(" ajax 編號:" + data.id + " , 姓名:" + data.name);
});
});
});
</script>
</head>
<body>
<div>
<button id="ajaxBtn">ajax</button>
</div>
<div id="msg">
</div>
</body>
</html>
$ .get 方法和$.post 方法
url 請求的 url 地址
data 發送的數據
callback 成功的回調函數
type 返回的數據類型
例子:
用到前面的student類和Baseservlet類
改善Basebean
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import java.io.IOException;
import java.lang.reflect.Method;
public class BaseServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("ajax 執行doget");
Student s=new Student(1,"name1");
Gson gson=new Gson();
String v=gson.toJson(s);
System.out.println(v);
resp.getWriter().write(v);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
// ajax請求
//get請求
$("#get").click(function(){
$.get(
"http://pc202004141500:8080/web3/BaseServlet",
"action=doGet",function(data){
$("#msg").html(" get編號:" + data.id + " , 姓名:" + data.name);},"json"
);
});
//post請求
$("#post").click(function(){
$.post(
"http://pc202004141500:8080/web3/BaseServlet",
"action=doGet",function(data){
$("#msg").html(" post編號:" + data.id + " , 姓名:" + data.name);},"json"
);
});
});
</script>
</head>
<body>
<div>
<button id ="get">get</button>
<button id ="post">post</button>
</div>
<div id="msg">
</div>
</body>
</html>
$.getJSON 方法
自動get請求json返回
url 請求的 url 地址
data 發送給服務器的數據
callback 成功的回調函數
用到前面的student類和Baseservlet類
例子:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#getjson").click(function(){
$.getJSON(
"http://pc202004141500:8080/web3/BaseServlet",
"action=doGet",function(data){
$("#msg").html(" getjson編號:" + data.id + " , 姓名:" + data.name);}
);
});
});
</script>
</head>
<body>
<div>
<button id ="getjson">getjson</button>
</div>
<div id="msg">
</div>
</body>
</html>
表單序列化 serialize()
serialize()可以把表單中所有表單項的內容都獲取到,並以 name=value&name=value 的形式進行拼接。
用到前面的student類和Baseservlet類
例子:
改善Baseservlet
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import java.io.IOException;
import java.lang.reflect.Method;
public class BaseServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(req.getParameter("username")+" "+req.getParameter("password"));
Student s=new Student(1,"name1");
Gson gson=new Gson();
String v=gson.toJson(s);
System.out.println(v);
resp.getWriter().write(v);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#sumbit").click(function(){
alert($("#form01").serialize());
$.getJSON(
"http://pc202004141500:8080/web3/BaseServlet",
"action=doGet&"+$("#form01").serialize(),function(data){
$("#msg").html(" getjson編號:" + data.id + " , 姓名:" + data.name);}
);
});
});
</script>
</head>
<body>
<div>
<button id ="sumbit">sumbit</button>
<form id="form01" >
用戶名:<input name="username" type="text" /><br/>
密碼:<input name="password" type="password" /><br/>
</form>
</div>
<div id="msg">
</div>
</body>
</html>
i18n 國際化
介紹
國際化(Internationalization)指的是同一個網站可以支持多種不同的語言,以方便不同國家,不同語種的用戶訪問。
關於國際化我們想到的最簡單的方案就是爲不同的國家創建不同的網站,比如蘋果公司,他的英文官網是: http://www.apple.com 而中國官網是 http://www.apple.com/cn
蘋果公司這種方案並不適合全部公司,而我們希望相同的一個網站,而不同人訪問的時候可以根據用戶所在的區域顯示 不同的語言文字,而網站的佈局樣式等不發生改變。
於是就有了我們說的國際化,國際化總的來說就是同一個網站不同國家的人來訪問可以顯示出不同的語言。但實際上這 種需求並不強烈,一般真的有國際化需求的公司,主流採用的依然是蘋果公司的那種方案,爲不同的國家創建不同的頁 面。所以國際化的內容我們瞭解一下即可。
國際化的英文 Internationalization,但是由於拼寫過長,老外想了一個簡單的寫法叫做 I18N,代表的是 Internationalization 這個單詞,以 I 開頭,以 N 結尾,而中間是 18 個字母,所以簡寫爲 I18N。以後我們說 I18N 和國際化是一個意思。
國際化相關要素介紹
配置文件
代碼實例:
package com.atguigu.i18n;
import org.junit.Test;
import java.util.Locale;
import java.util.ResourceBundle;
public class I18nTest {
@Test
public void testLocale(){
// 獲取你係統默認的語言。國家信息
// Locale locale = Locale.getDefault();
// System.out.println(locale);
// for (Locale availableLocale : Locale.getAvailableLocales()) {
// System.out.println(availableLocale);
// }
// 獲取中文,中文的常量的Locale對象
System.out.println(Locale.CHINA);
// 獲取英文,美國的常量的Locale對象
System.out.println(Locale.US);
}
@Test
public void testI18n(){
// 得到我們需要的Locale對象
Locale locale = Locale.CHINA;
// 通過指定的basename和Locale對象,讀取 相應的配置文件
ResourceBundle bundle = ResourceBundle.getBundle("i18n", locale);
System.out.println("username:" + bundle.getString("username"));
System.out.println("password:" + bundle.getString("password"));
System.out.println("Sex:" + bundle.getString("sex"));
System.out.println("age:" + bundle.getString("age"));
}
}
通過請求頭國際化頁面
結合前面的配置文件
jsp
<%@ page import="java.util.*" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<%Locale l=request.getLocale();
System.out.println(l);
ResourceBundle b = ResourceBundle.getBundle("i18n", l);
%>
<h1><%=b.getString("username") %></h1>
</body>
</html>
通過顯示的選擇語言類型進行國際化
<%@ page import="java.util.*" %>
<%@ page import="java.util.ResourceBundle" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
// 從請求頭中獲取Locale信息(語言)
Locale locale = null;
String country = request.getParameter("country");
if ("cn".equals(country)) {
locale = Locale.CHINA;
} else if ("usa".equals(country)) {
locale = Locale.US;
} else {
locale = request.getLocale();
}
System.out.println(locale);
// 獲取讀取包(根據 指定的baseName和Locale讀取 語言信息)
ResourceBundle i18n = ResourceBundle.getBundle("i18n", locale);
%>
<a href="i18n.jsp?country=cn">中文</a>|
<a href="i18n.jsp?country=usa">english</a>
<center>
<h1><%=i18n.getString("regist")%></h1>
<table>
<form>
<tr>
<td><%=i18n.getString("username")%></td>
<td><input name="username" type="text" /></td>
</tr>
<tr>
<td><%=i18n.getString("password")%></td>
<td><input type="password" /></td>
</tr>
<tr>
<td><%=i18n.getString("sex")%></td>
<td>
<input type="radio" /><%=i18n.getString("boy")%>
<input type="radio" /><%=i18n.getString("girl")%>
</td>
</tr>
<tr>
<td><%=i18n.getString("email")%></td>
<td><input type="text" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="reset" value="<%=i18n.getString("reset")%>" />
<input type="submit" value="<%=i18n.getString("submit")%>" /></td>
</tr>
</form>
</table>
<br /> <br /> <br /> <br />
</center>
國際化測試:
<br /> 1、訪問頁面,通過瀏覽器設置,請求頭信息確定國際化語言。
<br /> 2、通過左上角,手動切換語言
</body>
</html>
JSTL 標籤庫實現國際化
<%–1 使用標籤設置 Locale 信息–%>
<fmt:setLocale value="" />
<%–2 使用標籤設置 baseName–%>
<fmt:setBundle basename=""/>
<%–3 輸出指定 key 的國際化信息–%>
<fmt:message key="" />
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%response.setContentType("text/html; charset=utf-8"); %>
<%--1 使用標籤設置Locale信息--%>
<fmt:setLocale value="${param.locale}" />
<%--2 使用標籤設置baseName--%>
<fmt:setBundle basename="i18n"/>
<a href="i18n_fmt.jsp?locale=zh_CN">中文</a>|
<a href="i18n_fmt.jsp?locale=en_US">english</a>
<center>
<h1><fmt:message key="regist" /></h1>
<table>
<form>
<tr>
<td><fmt:message key="username" /></td>
<td><input name="username" type="text" /></td>
</tr>
<tr>
<td><fmt:message key="password" /></td>
<td><input type="password" /></td>
</tr>
<tr>
<td><fmt:message key="sex" /></td>
<td>
<input type="radio" /><fmt:message key="boy" />
<input type="radio" /><fmt:message key="girl" />
</td>
</tr>
<tr>
<td><fmt:message key="email" /></td>
<td><input type="text" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="reset" value="<fmt:message key="reset" />" />
<input type="submit" value="<fmt:message key="submit" />" /></td>
</tr>
</form>
</table>
<br /> <br /> <br /> <br />
</center>
</body>
</html>