JSON、AJAX、i18n学习总结
一、JSON
- JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。JSON采用完全独立于语言的文本格式,而且很多语言都提供了对 json 的支持(包括 C, C++, C#, Java, JavaScript, Perl, Python等)。 这样就使得 JSON 成为理想的数据交换格式。
- json 是一种轻量级的数据交换格式。
- 轻量级指的是跟 xml 做比较。
- 数据交换指的是客户端和服务器之间业务数据的传递格式
1.1 JSON在JavaScript中的使用。
1.1.1 json的定义
json 是由键值对组成,并且由花括号(大括号)包围。每个键由引号引起来,键和值之间使用冒号进行分隔,多组键值对之间进行逗号进行分隔。
json定义示例:
<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"
}],
}
</script>
1.1.2 json的访问
json 本身是一个对象。
json 中的 key 我们可以理解为是对象中的一个属性。
json 中的 key 访问就跟访问对象的属性一样:
json 对象.key
json访问示例:
<script type="text/javascript">
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);//[object Object]
alert(jsonObj.key5.key5_2);//key5_2_value
//取出每一个元素都是json对象
var jsonItem = jsonObj.key6[0];
alert(jsonItem.key6_1_2);//key6_1_2_value
</script>
1.1.3 json的两个常用方法
json 的存在有两种形式
一种是:对象的形式存在,我们叫它 json 对象。
一种是:字符串的形式存在,我们叫它 json 字符串。
一般我们要操作 json 中的数据的时候,需要 json 对象的格式。
一般我们要在客户端和服务器之间进行数据交换的时候,使用 json 字符串。
JSON.stringify() 把 json 对象转换成为 json 字符串
JSON.parse() 把 json 字符串转换成为 json 对象
<script type="text/javascript">
//把json对象转换成为json字符串,类似于java中对象的toString
var jsonObjString = JSON.stringify(jsonObj);//{"key1":12,"key2":true,"key3":"abc","key4":[11,"arr",false]}
alert(jsonObjString);
//把json字符串,转换成为json对象
var jsonObj2 = JSON.parse(jsonObjString);
alert(jsonObj2);//[object Object]
</script>
1.2 JSON在java中的使用
以使用Gson JAR包进行转换
GSON是Google提供的用来在Java对象和JSON数据之间进行映射的Java类库。可以将一个Json字符转成一个Java对象,或者将一个Java转化为Json字符串
两个方法:
- public String toJson(Objcet obj)方法,可以将对象转化为json字符串
- public T fromJson(String jsonStr,T.class)方法,可以将json字符串转化为Java对象
首先需要导入gson-2.2.4.jar包
1.2.1 javaBean和json的互转
//1.javaBean和json的互转
@Test
public void test1(){
Person person = new Person(1,"国哥好帅!");
//创建Gson对象实例
Gson gson = new Gson();
//toJson方法可以把java对象转换成为json字符串
String personJsonString = gson.toJson(person);
System.out.println(personJsonString);//{"id":1,"name":"国哥好帅!"}
//fromJson把json字符串转换会Java对象
//第一个参数是json字符串
//第二个参数是转换回去的java对象类型
Person person1 = gson.fromJson(personJsonString, Person.class);
System.out.println(person1);
}
1.2.2 List和json的互转
TypeToken介绍:
TypeToken,它是gson提供的数据类型转换器,可以支持各种数据集合类型转换。
先调用TypeToken的构造器得到匿名内部类,再由该匿名内部类对象调用getType()方法得到要转换成的type
方法一:
class PersonListType extends TypeToken<ArrayList<Person>>{
}
public class JsonTest {
//2.List和json的互转
@Test
public void test2(){
List<Person> personList = new ArrayList<>();
personList.add(new Person(1,"国哥"));
personList.add(new Person(2,"康师傅"));
Gson gson = new Gson();
//把List转换为json字符串
String personListJsonString = gson.toJson(personList);
System.out.println(personListJsonString);//[{"id":1,"name":"国哥"},{"id":2,"name":"康师傅"}]
//将json字符串转换为List
List<Person> list= gson.fromJson(personListJsonString, new PersonListType().getType());
System.out.println(list);
}
}
方法二:(匿名内部类)
//2.List和json的互转
@Test
public void test2(){
List<Person> personList = new ArrayList<>();
personList.add(new Person(1,"国哥"));
personList.add(new Person(2,"康师傅"));
Gson gson = new Gson();
//把List转换为json字符串
String personListJsonString = gson.toJson(personList);
System.out.println(personListJsonString);
//将json字符串转换为List
List<Person> list= gson.fromJson(personListJsonString, new TypeToken<ArrayList<Person>>(){
}.getType());//使用匿名内部类
System.out.println(list);
}
1.2.3 map和json的互转
//3.map和json的互转
@Test
public void test3(){
Map<Integer,Person> personMap = new HashMap<>();
personMap.put(1,new Person(1,"国哥好帅"));
personMap.put(2,new Person(1,"康师傅也好帅"));
Gson gson = new Gson();
//把map集合转换成为json字符串
String personMapJsonString = gson.toJson(personMap);
System.out.println(personMapJsonString);
//将json字符串转换为map集合
Map<Integer,Person> personMap2= gson.fromJson(personMapJsonString, new TypeToken<Map<Integer, Person>>(){
}.getType());
System.out.println(personMap2);
}
二、AJAX请求
2.1 AJAX 简介
- AJAX 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式网页应用的网页开发技术。
- ajax 是一种浏览器通过 js 异步发起请求,局部更新页面的技术。
- Ajax 请求的局部更新,浏览器地址栏不会发生变化
- 局部更新不会舍弃原来页面的内容
同步和异步处理的问题:
-
同步处理:
请求:发送二次请求时,只能等上次请求响应后,才能执行 效率:就算我们需要刷新局部,也必须刷新整个页面
-
异步处理:
请求:aJax请求不会影响其他请求 效率:局部刷新
2.2 javaScript 原生 Ajax 请求
2.2.1 原生的 Ajax 请求使用步骤
1、我们首先要创建 XMLHttpRequest 对象
2、调用 open 方法设置请求参数
3、调用 send 方法发送请求
4、在 send 方法前绑定 onreadystatechange 事件,处理请求完成后的操作。
代码示例:
<!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://localhost:8080/16_json_ajax_i18n/ajaxServlet?action=javaScriptAjax",true);
// 3、在send方法前绑定onreadystatechange事件,处理请求完成后的操作。
xmlHttpRequest.onreadystatechange = function(){
//当 readyState 等于 4 且状态为 200 时,表示响应已就绪
if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){
alert(xmlHttpRequest.responseText);
var jsonObj = JSON.parse(xmlHttpRequest.responseText);
//把响应的数据显示在页面上
document.getElementById("div01").innerHTML = "编号:"+jsonObj.id+",姓名:"+jsonObj.name;
}
}
// 4、调用send方法发送请求
xmlHttpRequest.send();
}
</script>
</head>
<body>
<button onclick="ajaxRequest()">ajax request</button>
<div id="div01">
</div>
</body>
</html>
创建一个 AjaxServlet 程序接收请求:
public class AjaxServlet extends BaseServlet {
protected void javaScriptAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html; charset=UTF-8");
System.out.println("Ajax请求过来了");
Person person = new Person(1,"国哥");
//json格式字符串
Gson gson = new Gson();
String personJson = gson.toJson(person);
resp.getWriter().write(personJson);
}
}
2.2.2 XMLHttpRequest介绍
XMLHttpRequest的介绍:
- XMLHttpRequest对象是AJAX中非常重要的对象,所有的AJAX操作都是基于该对象的。
- XMLHttpRequest对象用来封装请求报文,我们向服务器发送的请求信息全部都需要封装到该对象中。
- 获取XMLHttpRequest对象:
var xmlHttpRequest= new XMLHttpRequest(); //目前主流浏览器都支持
注意:XMLHttpRequest对象并没有成为标准,但是现在的主流浏览器都支持该对象,而一些如IE6的老版本浏览器中的创建方式有一些区别,但是问题不大。
XMLHttpRequest对象的方法:
XMLHttpRequest对象的属性:
2.3 jQuery中的AJAX请求
2.3.1 $.ajax()方式
$.ajax({
type:"请求方式",
url:"请求路径",
data:"请求携带参数数据",
/*格式有两种:
一:name=value&name=value
二:{key:value}*/
dataType:"服务器预期返回值类型,如:'text','json','xml','html'",
/*常用的数据类型有:
text 表示纯文本
xml 表示xml数据
json 表示json对象*/
success:function(){
//请求成功时,被回调
},
error:function(){
//请求失败时,被回调
}
});
代码示例:
// ajax请求
$("#ajaxBtn").click(function(){
$.ajax({
url:"http://localhost:8080/16_json_ajax_i18n/ajaxServlet",
data:"action=jQueryAjax",//写成{action:"jQueryAjax"}也可
type:"GET",
success:function(data){
$("#msg").html("编号:"+data.id+",姓名:"+data.name);
},
dataType:"json"
});
});
2.3.2 $.get()和 $.post()方式
$.get(url, [data], [callback], [type])
url:待载入页面的URL地址
data:待发送 Key/value 参数。
callback:载入成功时回调函数。
type:返回内容格式,xml, html, script, json, text, _default。
// ajax--get请求
$("#getBtn").click(function(){
$.get("http://localhost:8080/16_json_ajax_i18n/ajaxServlet","action=jQueryGet",function(data){
$("#msg").html("get 编号:"+data.id+",姓名:"+data.name);
},"json");
});
$.post(url, [data], [callback], [type])
url:发送请求地址。
data:待发送 Key/value 参数。
callback:发送成功时回调函数。
type:返回内容格式,xml, html, script, json, text, _default。
// ajax--post请求
$("#postBtn").click(function(){
$.get("http://localhost:8080/16_json_ajax_i18n/ajaxServlet","action=jQueryPost",function(data){
$("#msg").html("post 编号:"+data.id+",姓名:"+data.name);
},"json");
});
2.3.3 $.getJSON()方式
$.getJSON(url, [data], [callback])
url:发送请求地址。
data:待发送 Key/value 参数。
callback:载入成功时回调函数
通过 HTTP GET 请求载入 JSON 数据(get请求,返回类型为json类型)
代码示例:
// ajax--getJson请求
$("#getJSONBtn").click(function(){
$.getJSON("http://localhost:8080/16_json_ajax_i18n/ajaxServlet","action=jQueryGetJSON",function(data){
$("#msg").html("getJSONBtn 编号:"+data.id+",姓名:"+data.name);
});
});
2.3.4 表单序列化 serialize()
serialize()可以把表单中所有表单项的内容都获取到,并以 name=value&name=value 的形式进行拼接。
// ajax请求
$("#submit").click(function(){
// 把参数序列化
var formData = $("#form01").serialize();
$.getJSON("http://localhost:8080/16_json_ajax_i18n/ajaxServlet","action=jQuerySerialize&"+formData,function(data){
console.log(data);
$("#msg").html("Serialize 姓名:"+data.username+",密码:"+data.password);
})
});
servlet代码:
protected void jQuerySerialize(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("jQuerySerialize == 方法调用了");
String username = req.getParameter("username");
String password = req.getParameter("password");
Map<String,String> form = new HashMap<String,String>();
form.put("username",username);
form.put("password",password);
Gson gson = new Gson();
String formJsonString = gson.toJson(form);
System.out.println(formJsonString);
resp.getWriter().write(formJsonString);
}
三、i18n国际化(了解)
3.1 什么是i18n国际化?
- 国际化(Internationalization)指的是同一个网站可以支持多种不同的语言,以方便不同国家,不同语种的用户访问。
- 关于国际化我们想到的最简单的方案就是为不同的国家创建不同的网站,比如苹果公司,他的英文官网是:http://www.apple.com 而中国官网是 http://www.apple.com/cn
- 苹果公司这种方案并不适合全部公司,而我们希望相同的一个网站,而不同人访问的时候可以根据用户所在的区域显示
不同的语言文字,而网站的布局样式等不发生改变。 - 于是就有了我们说的国际化,国际化总的来说就是同一个网站不同国家的人来访问可以显示出不同的语言。但实际上这种需求并不强烈,一般真的有国际化需求的公司,主流采用的依然是苹果公司的那种方案,为不同的国家创建不同的页面。所以国际化的内容我们了解一下即可。
- 国际化的英文 Internationalization,但是由于拼写过长,老外想了一个简单的写法叫做 I18N,代表的是 Internationalization这个单词,以 I 开头,以 N 结尾,而中间是 18 个字母,所以简写为 I18N。以后我们说 I18N 和国际化是一个意思。
3.2 国际化相关要素介绍
3.3 国际化资源properties测试
配置两个语言的配置文件:(命名规范:基础名_语言代码_国家代码.properties)
i18n_en_US.properties 英文
username=username
password=password
sex=sex
age=age
regist=regist
boy=boy
email=email
girl=girl
reset=reset
submit=submit
i18n_zh_CN.properties 中文
username= 用户名
password= 密码
sex= 性别
age= 年龄
regist= 注册
boy= 男
girl= 女
email= 邮箱
reset= 重置
submit= 提交
国际化测试代码:
public class I18nTest {
@Test
public void testLocale(){
//获得此 Java 虚拟机实例的当前默认语言环境值
Locale locale = Locale.getDefault();
System.out.println(locale);//zh_CN
// //输出全部的语言环境值
// for(Locale l : Locale.getAvailableLocales()){
// System.out.println(l);
// }
//输出中文的语言环境值
System.out.println(Locale.CHINA);//zh_CN
//输出英文的语言环境值
System.out.println(Locale.US);//en_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"));
}
}
3.3 通过请求头国际化页面
设置浏览器的语言
代码示例:
<%@ page import="java.util.Locale" %>
<%@ 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 = request.getLocale();
//获取读取包(根据指定的baseName和Locale读取语言信息)
ResourceBundle i18n = ResourceBundle.getBundle("i18n",locale);
%>
<a href="">中文</a>|
<a href="">english</a>
<center>
<h1>注册</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>
3.4 通过显示的选择语言类型进行国际化
<%@ page import="java.util.Locale" %>
<%@ 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 = request.getLocale();
String country = request.getParameter("country");
if("cn".equals(country)){
locale = Locale.CHINA;
}else if("usa".equals(country)){
locale = Locale.US;
}else{
locale = request.getLocale();
}
//获取读取包(根据指定的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>注册</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>
3.5 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>
<%--1 使用标签设置Locale信息--%>
<fmt:setLocale value="${param.locale}"/>
<%--2 使用标签设置baseName--%>
<fmt:setBundle basename="i18n"/>
<%--3 使用标签输出国际化信息--%>
<fmt:message key="username"/>
<a href="i18n_fmt.jsp?locale=zh_CN">中文</a>|
<a href="i18n_fmt.jsp?locale=en_US">english</a>
<center>
<h1>注册</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>