1、什么是 JSON?

JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。JSON 采用完全独立于语言的文本格式,而且很多语言都提供了对 json 的支持(包括 C, C++, C#, Java, JavaScript, Perl, Python 等)。 这样就使得 JSON 成为理想的数据交换格式。

json 是一种轻量级的数据交换格式。 轻量级指的是跟 xml 做比较。 数据交换指的是客户端和服务器之间业务数据的传递格式。

JSON 在 JavaScript 中的使用

1、json的定义

json 是由键值对组成,并且由花括号(大括号)包围。每个键由引号引起来,键和值之间使用冒号进行分隔, 多组键值对之间进行逗号进行分隔。

json定义示例:

  1. var jsonObj = {
  2. "key1":12,
  3. "key2":"abc",
  4. "key3":true,
  5. "key4":[11,"arr",false],
  6. "key5":{
  7. "key5_1" : 551,
  8. "key5_2" : "key5_2_value"
  9. },
  10. "key6":[{
  11. "key6_1_1":6611,
  12. "key6_1_2":"key6_1_2_value"
  13. },{
  14. "key6_2_1":6621,
  15. "key6_2_2":"key6_2_2_value"
  16. }]
  17. };

2、json的访问

json 本身是一个对象。 json 中的 key 我们可以理解为是对象中的一个属性。 json 中的 key 访问就跟访问对象的属性一样: json 对象.key

json访问示例:

  1. alert(typeof(jsonObj));// object json 就是一个对象
  2. alert(jsonObj.key1); //12
  3. alert(jsonObj.key2); // abc
  4. alert(jsonObj.key3); // true
  5. alert(jsonObj.key4);// 得到数组[11,"arr",false]
  6. // json 中 数组值的遍历
  7. for(var i = 0; i < jsonObj.key4.length; i++) {
  8. alert(jsonObj.key4[i]);
  9. }
  10. alert(jsonObj.key5.key5_1);//551
  11. alert(jsonObj.key5.key5_2);//key5_2_value
  12. alert( jsonObj.key6 );// 得到 json 数组
  13. // 取出来每一个元素都是 json 对象
  14. var jsonItem = jsonObj.key6[0];
  15. // alert( jsonItem.key6_1_1 ); //6611
  16. alert( jsonItem.key6_1_2 ); //key6_1_2_value

3、json 的两个常用方法

json 的存在有两种形式。 一种是:对象的形式存在,我们叫它 json 对象。 一种是:字符串的形式存在,我们叫它 json 字符串。 一般我们要操作 json 中的数据的时候,需要 json 对象的格式。 一般我们要在客户端和服务器之间进行数据交换的时候,使用 json 字符串。

JSON.stringify() 把 json 对象转换成为 json 字符串 JSON.parse() 把 json 字符串转换成为 json 对象

示例代码

  1. // 把 json 对象转换成为 json 字符串
  2. var jsonObjString = JSON.stringify(jsonObj); // 特别像 Java 中对象的 toString
  3. alert(jsonObjString)
  4. // 把 json 字符串。转换成为 json 对象
  5. var jsonObj2 = JSON.parse(jsonObjString);
  6. alert(jsonObj2.key1);// 12
  7. alert(jsonObj2.key2);// abc

JSON在Java中的使用

1、JavaBean 和 json 的互转

  1. @Test
  2. public void test1(){
  3. Person person = new Person(1,"国哥好帅!");
  4. // 创建 Gson 对象实例
  5. Gson gson = new Gson();
  6. // toJson 方法可以把 java 对象转换成为 json 字符串
  7. String personJsonString = gson.toJson(person);
  8. System.out.println(personJsonString);
  9. // fromJson 把 json 字符串转换回 Java 对象
  10. // 第一个参数是 json 字符串
  11. // 第二个参数是转换回去的 Java 对象类型
  12. Person person1 = gson.fromJson(personJsonString, Person.class);
  13. System.out.println(person1);
  14. }

2、List 和 json 的互转

  1. // 1.2.2、List 和 json 的互转
  2. @Test
  3. public void test2() {
  4. List<Person> personList = new ArrayList<>();
  5. personList.add(new Person(1, "国哥"));
  6. personList.add(new Person(2, "康师傅"));
  7. Gson gson = new Gson();
  8. // 把 List 转换为 json 字符串
  9. String personListJsonString = gson.toJson(personList);
  10. System.out.println(personListJsonString);
  11. List<Person> list = gson.fromJson(personListJsonString, new PersonListType().getType());
  12. System.out.println(list);
  13. Person person = list.get(0);
  14. System.out.println(person);
  15. }

3、map 和 json 的互转

  1. // 1.2.3、map 和 json 的互转
  2. @Test
  3. public void test3(){
  4. Map<Integer,Person> personMap = new HashMap<>();
  5. personMap.put(1, new Person(1, "国哥好帅"));
  6. personMap.put(2, new Person(2, "康师傅也好帅"));
  7. Gson gson = new Gson();
  8. // 把 map 集合转换成为 json 字符串
  9. String personMapJsonString = gson.toJson(personMap);
  10. System.out.println(personMapJsonString);
  11. // Map<Integer,Person> personMap2 = gson.fromJson(personMapJsonString, new
  12. PersonMapType().getType());
  13. Map<Integer,Person> personMap2 = gson.fromJson(personMapJsonString, new
  14. TypeToken<HashMap<Integer,Person>>(){}.getType());
  15. System.out.println(personMap2);
  16. Person p = personMap2.get(1);
  17. System.out.println(p);
  18. }

2、AJAX请求

什么是AJAX请求

AJAX 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式网页应用的网页开发技术。 Ajax 是一种浏览器通过 js 异步发起请求,局部更新页面的技术。

Ajax 请求的局部更新,浏览器地址栏不会发生变化 局部更新不会舍弃原来页面的内容

原生 AJAX 请求的示例:

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  2. <html>
  3. <head>
  4. <meta http-equiv="pragma" content="no-cache"/>
  5. <meta http-equiv="cache-control" content="no-cache"/>
  6. <meta http-equiv="Expires" content="0"/>
  7. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  8. <title>Insert title here</title>
  9. <script type="text/javascript">
  10. // 在这里使用 javaScript 语言发起 Ajax 请求,访问服务器 AjaxServlet 中 javaScriptAjax
  11. function ajaxRequest() {
  12. // 1、我们首先要创建 XMLHttpRequest
  13. var xmlhttprequest = new XMLHttpRequest();
  14. // 2、调用 open 方法设置请求参数
  15. xmlhttprequest.open("GET", "http://localhost:8080/16_json_ajax_i18n/ajaxServlet?action=javaScriptAjax",true);
  16. // 4、在 send 方法前绑定 onreadystatechange 事件,处理请求完成后的操作。
  17. xmlhttprequest.onreadystatechange = function () {
  18. if (xmlhttprequest.readyState == 4 && xmlhttprequest.status == 200) {
  19. var jsonObj = JSON.parse(xmlhttprequest.responseText);
  20. // 把响应的数据显示在页面上
  21. document.getElementById("div01").innerHTML = "编号:" + jsonObj.id + " , 姓名:" +
  22. jsonObj.name;
  23. }
  24. };
  25. // 3、调用 send 方法发送请求
  26. xmlhttprequest.send();
  27. }
  28. </script>
  29. </head>
  30. <body>
  31. <button onclick="ajaxRequest()">ajax request</button>
  32. <div id="div01">
  33. </div>
  34. </body>
  35. </html>

jQuery中的Ajax请求

$.ajax 方法 url 表示请求的地址 type 表示请求的类型 GET 或 POST 请求 data 表示发送给服务器的数据 格式有两种: 一:name=value&name=value 二:{key:value} success 请求成功,响应的回调函数 dataType 响应的数据类型 常用的数据类型有: text 表示纯文本 xml 表示 xml 数据 json 表示 json 对象

  1. $("#ajaxBtn").click(function(){
  2. $.ajax({
  3. url:"http://localhost:8080/16_json_ajax_i18n/ajaxServlet",
  4. // data:"action=jQueryAjax",
  5. data:{action:"jQueryAjax"},
  6. type:"GET",
  7. success:function (data) {
  8. // alert("服务器返回的数据是:" + data);
  9. // var jsonObj = JSON.parse(data);
  10. $("#msg").html("编号:" + data.id + " , 姓名:" + data.name);
  11. },
  12. dataType : "json"
  13. });
  14. });
  1. $.get 方法和$.post 方法

url 请求的 url 地址 data 发送的数据 callback 成功的回调函数 type 返回的数据类型

  1. // ajax--get 请求
  2. $("#getBtn").click(function(){
  3. $.get("http://localhost:8080/16_json_ajax_i18n/ajaxServlet","action=jQueryGet",function (data) {
  4. $("#msg").html(" get 编号:" + data.id + " , 姓名:" + data.name);
  5. },"json");
  6. });
  7. // ajax--post 请求
  8. $("#postBtn").click(function(){
  9. $.post("http://localhost:8080/16_json_ajax_i18n/ajaxServlet","action=jQueryPost",function (data){
  10. $("#msg").html(" post 编号:" + data.id + " , 姓名:" + data.name);
  11. },"json");
  12. });
  1. $.getJSON 方法

url 请求的 url 地址 data 发送给服务器的数据 callback 成功的回调函数

  1. // ajax--getJson 请求
  2. $("#getJSONBtn").click(function(){
  3. $.getJSON("http://localhost:8080/16_json_ajax_i18n/ajaxServlet","action=jQueryGetJSON",function(data) {
  4. $("#msg").html(" getJSON 编号:" + data.id + " , 姓名:" + data.name);
  5. });
  6. });

表单序列化 serialize()

serialize()可以把表单中所有表单项的内容都获取到,并以 name=value&name=value 的形式进行拼接。

  1. // ajax 请求
  2. $("#submit").click(function(){
  3. // 把参数序列化
  4. $.getJSON("http://localhost:8080/16_json_ajax_i18n/ajaxServlet","action=jQuerySerialize&" +
  5. $("#form01").serialize(),function (data) {
  6. $("#msg").html(" Serialize 编号:" + data.id + " , 姓名:" + data.name);
  7. });
  8. });

3、i18n国际化(了解内容)

什么是 i18n 国际化

  1. 国际化(Internationalization)指的是同一个网站可以支持多种不同的语言,以方便不同国家,不同语种的用户访问。

  2. 关于国际化我们想到的最简单的方案就是为不同的国家创建不同的网站,比如苹果公司,他的英文官网是:

    1. http://www.apple.com 而中国官网是 http://www.apple.com/cn
  3. 苹果公司这种方案并不适合全部公司,而我们希望相同的一个网站,而不同人访问的时候可以根据用户所在的区域显示不同的语言文字,而网站的布局样式等不发生改变。

  1. 于是就有了我们说的国际化,国际化总的来说就是同一个网站不同国家的人来访问可以显示出不同的语言。但实际上这 种需求并不强烈,一般真的有国际化需求的公司,主流采用的依然是苹果公司的那种方案,为不同的国家创建不同的页 面。所以国际化的内容我们了解一下即可。
  1. 国际化的英文 Internationalization,但是由于拼写过长,老外想了一个简单的写法叫做 I18N,代表的是 Internationalization 这个单词,以 I 开头,以 N 结尾,而中间是 18 个字母,所以简写为 I18N。以后我们说 I18N 和国际化是一个意思。

国际化相关要素介绍

image.png

国际化资源 properties 测试

image.png

国际化测试代码:

  1. public class I18nTest {
  2. @Test
  3. public void testLocale() {
  4. // 获取你系统默认的语言。国家信息
  5. // Locale locale = Locale.getDefault();
  6. // System.out.println(locale);
  7. // for (Locale availableLocale : Locale.getAvailableLocales()) {
  8. // System.out.println(availableLocale);
  9. // }
  10. // 获取中文,中文的常量的 Locale 对象
  11. System.out.println(Locale.CHINA);
  12. // 获取英文,美国的常量的 Locale 对象
  13. System.out.println(Locale.US);
  14. }
  15. @Test
  16. public void testI18n() {
  17. // 得到我们需要的 Locale 对象
  18. Locale locale = Locale.CHINA;
  19. // 通过指定的 basename 和 Locale 对象,读取 相应的配置文件
  20. ResourceBundle bundle = ResourceBundle.getBundle("i18n", locale);
  21. System.out.println("username:" + bundle.getString("username"));
  22. System.out.println("password:" + bundle.getString("password"));
  23. System.out.println("Sex:" + bundle.getString("sex"));
  24. System.out.println("age:" + bundle.getString("age"));
  25. }
  26. }

通过请求头国际化页面

  1. <%@ page import="java.util.Locale" %>
  2. <%@ page import="java.util.ResourceBundle" %>
  3. <%@ page language="java" contentType="text/html; charset=UTF-8"
  4. pageEncoding="UTF-8" %>
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  6. <html>
  7. <head>
  8. <meta http-equiv="pragma" content="no-cache"/>
  9. <meta http-equiv="cache-control" content="no-cache"/>
  10. <meta http-equiv="Expires" content="0"/>
  11. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  12. <title>Insert title here</title>
  13. </head>
  14. <body>
  15. <%
  16. // 从请求头中获取 Locale 信息(语言)
  17. Locale locale = request.getLocale();
  18. System.out.println(locale);
  19. // 获取读取包(根据 指定的 baseName 和 Locale 读取 语言信息)
  20. ResourceBundle i18n = ResourceBundle.getBundle("i18n", locale);
  21. %>
  22. <a href="">中文</a>|
  23. <a href="">english</a>
  24. <center>
  25. <h1><%=i18n.getString("regist")%>
  26. </h1>
  27. <table>
  28. <form>
  29. <tr>
  30. <td><%=i18n.getString("username")%>
  31. </td>
  32. <td><input name="username" type="text"/></td>
  33. </tr>
  34. <tr>
  35. <td><%=i18n.getString("password")%>
  36. </td>
  37. <td><input type="password"/></td>
  38. </tr>
  39. <tr>
  40. <td><%=i18n.getString("sex")%>
  41. </td>
  42. <td>
  43. <input type="radio"/><%=i18n.getString("boy")%>
  44. <input type="radio"/><%=i18n.getString("girl")%>
  45. </td>
  46. </tr>
  47. <tr>
  48. <td><%=i18n.getString("email")%>
  49. </td>
  50. <td><input type="text"/></td>
  51. </tr>
  52. <tr>
  53. <td colspan="2" align="center">
  54. <input type="reset" value="<%=i18n.getString("reset")%>"/>&nbsp;&nbsp;
  55. <input type="submit" value="<%=i18n.getString("submit")%>"/></td>
  56. </tr>
  57. </form>
  58. </table>
  59. <br/> <br/> <br/> <br/>
  60. </center>
  61. 国际化测试:
  62. <br/> 1、访问页面,通过浏览器设置,请求头信息确定国际化语言。
  63. <br/> 2、通过左上角,手动切换语言
  64. </body>
  65. </html>

通过显示的选择语言类型进行国际化

  1. <%@ page import="java.util.Locale" %>
  2. <%@ page import="java.util.ResourceBundle" %>
  3. <%@ page language="java" contentType="text/html; charset=UTF-8"
  4. pageEncoding="UTF-8" %>
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  6. <html>
  7. <head>
  8. <meta http-equiv="pragma" content="no-cache"/>
  9. <meta http-equiv="cache-control" content="no-cache"/>
  10. <meta http-equiv="Expires" content="0"/>
  11. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  12. <title>Insert title here</title>
  13. </head>
  14. <body>
  15. <%
  16. // 从请求头中获取 Locale 信息(语言)
  17. Locale locale = null;
  18. String country = request.getParameter("country");
  19. if ("cn".equals(country)) {
  20. locale = Locale.CHINA;
  21. } else if ("usa".equals(country)) {
  22. locale = Locale.US;
  23. } else {
  24. locale = request.getLocale();
  25. }
  26. System.out.println(locale);
  27. // 获取读取包(根据 指定的 baseName 和 Locale 读取 语言信息)
  28. ResourceBundle i18n = ResourceBundle.getBundle("i18n", locale);
  29. %>
  30. <a href="i18n.jsp?country=cn">中文</a>|
  31. <a href="i18n.jsp?country=usa">english</a>
  32. <center>
  33. <h1><%=i18n.getString("regist")%>
  34. </h1>
  35. <table>
  36. <form>
  37. <tr>
  38. <td><%=i18n.getString("username")%>
  39. </td>
  40. <td><input name="username" type="text"/></td>
  41. </tr>
  42. <tr>
  43. <td><%=i18n.getString("password")%>
  44. </td>
  45. <td><input type="password"/></td>
  46. </tr>
  47. <tr>
  48. <td><%=i18n.getString("sex")%>
  49. </td>
  50. <td>
  51. <input type="radio"/><%=i18n.getString("boy")%>
  52. <input type="radio"/><%=i18n.getString("girl")%>
  53. </td>
  54. </tr>
  55. <tr>
  56. <td><%=i18n.getString("email")%>
  57. </td>
  58. <td><input type="text"/></td>
  59. </tr>
  60. <tr>
  61. <td colspan="2" align="center">
  62. <input type="reset" value="<%=i18n.getString("reset")%>"/>&nbsp;&nbsp;
  63. <input type="submit" value="<%=i18n.getString("submit")%>"/></td>
  64. </tr>
  65. </form>
  66. </table>
  67. <br/> <br/> <br/> <br/>
  68. </center>
  69. 国际化测试:
  70. <br/> 1、访问页面,通过浏览器设置,请求头信息确定国际化语言。
  71. <br/> 2、通过左上角,手动切换语言
  72. </body>
  73. </html>

JSTL 标签库实现国际化

image.png

  1. <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
  2. <%@ page language="java" contentType="text/html; charset=UTF-8"
  3. pageEncoding="UTF-8" %>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  5. <html>
  6. <head>
  7. <meta http-equiv="pragma" content="no-cache"/>
  8. <meta http-equiv="cache-control" content="no-cache"/>
  9. <meta http-equiv="Expires" content="0"/>
  10. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  11. <title>Insert title here</title>
  12. </head>
  13. <body>
  14. <%--1 使用标签设置 Locale 信息--%>
  15. <fmt:setLocale value="${param.locale}"/>
  16. <%--2 使用标签设置 baseName--%>
  17. <fmt:setBundle basename="i18n"/>
  18. <a href="i18n_fmt.jsp?locale=zh_CN">中文</a>|
  19. <a href="i18n_fmt.jsp?locale=en_US">english</a>
  20. <center>
  21. <h1><fmt:message key="regist"/></h1>
  22. <table>
  23. <form>
  24. <tr>
  25. <td><fmt:message key="username"/></td>
  26. <td><input name="username" type="text"/></td>
  27. </tr>
  28. <tr>
  29. <td><fmt:message key="password"/></td>
  30. <td><input type="password"/></td>
  31. </tr>
  32. <tr>
  33. <td><fmt:message key="sex"/></td>
  34. <td>
  35. <input type="radio"/><fmt:message key="boy"/>
  36. <input type="radio"/><fmt:message key="girl"/>
  37. </td>
  38. </tr>
  39. <tr>
  40. <td><fmt:message key="email"/></td>
  41. <td><input type="text"/></td>
  42. </tr>
  43. <tr>
  44. <td colspan="2" align="center">
  45. <input type="reset" value="<fmt:message key="reset" />"/>&nbsp;&nbsp;
  46. <input type="submit" value="<fmt:message key="submit" />"/></td>
  47. </tr>
  48. </form>
  49. </table>
  50. <br/> <br/> <br/> <br/>
  51. </center>
  52. </body>
  53. </html>