JavaWeb基础-10.JSON&AJAX&i18n

本文介绍了JSON在JavaScript和Java中的使用,包括JSON对象的定义、访问方式及转换方法。接着讲解了AJAX的基本概念、原生与jQuery中的实现。最后探讨了i18n国际化,包括其简介、实现要素和具体应用。
摘要由CSDN通过智能技术生成

1. JSON

  • JSON(JavaScript Object Notation)是一种轻量级的数据交换格式。易于人类阅读和编写,也易于机器解析。JSON采用完全独立于语言的文本格式,而且很多语言都提供了JSON的支持
  • JSON是一种轻量级的数据交换格式
  • 轻量级指的是跟xml做比较
  • 数据交换指的是客户端和服务器间业务数据的传递格式

1.1 JSON在JavaScript中的使用

1.1.1 JSON的定义

  • JSON是由键值对组成,并且由大括号包围,每个键由引号引起来,键和值之间使用冒号进行分割,多组键值对间进行逗号进行分割
<!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": "key552value"
            },
            "key6": [{
                "key6-1-1": 6611,
                "key6-1-2": "6622"
            }, {
                "key6-2-1": 6622,
                "key6-2-2": "value"
            }]
        };
</script>
</head>
<body>

</body>
</html>

1.1.2 JSON的访问

  • Json本身是一个对象
  • json中的key可以理解为对象中的一个属性
  • json中的key访问就跟访问对象的属性一样,json.key
 //alert(typeof (jsonObj));//json就是一个对象
        // json的访问
        //alert(jsonObj.key1);
        //alert(jsonObj.key2);
        //alert(jsonObj.key3);
        //alert(jsonObj.key4);
        // for (var i = 0; i < jsonObj.key4.length; i++) {
        //     alert(jsonObj.key4[i]);
        // }
        alert(jsonObj.key5["key5-2"]);
        alert(jsonObj.key6[1]["key6-2-1"]);

1.1.3 JSON的两个常用方法

  • JSON的存在由两种形式
  • 一种是对象的形式存在,我们叫他JSON对象
  • 一种是字符串的形式存在,我们叫他JSON字符串
  • 一般我们要操作json中的数据时,需要json对象的格式
  • 一般我们要在客户端和服务器间进行数据交换时,使用json字符串
  • JSON.stringify() 把json对象转换为json字符串
  • JSON.parse() 把json字符串转换为json对象
// json对象转字符串
        var jsonObjString = JSON.stringify(jsonObj);//类似Java中对象的toString
        alert(jsonObjString);
        // json字符串转json对象
        var obj = JSON.parse(jsonObjString);
        alert(obj);

1.2 JSON在Java中的使用

1.2.1 javaBean和json的互转

public class Person {

    private Integer id;
    private String name;

    public Person() {
    }

    public Person(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

	@Test
    public void test1() {
        Person person = new Person(1, "zhang");
        //创建gson对象实例
        Gson gson = new Gson();
        //toJson方法可以把java对象转换成json字符串
        String perJsonStr = gson.toJson(person);
        System.out.println(perJsonStr);
        //fromJson把json字符串转换JAVA对象
        Person person1 = gson.fromJson(perJsonStr, Person.class);
        System.out.println(person1);
    }

1.2.2 List和json的互转

public class PersonListType extends TypeToken<ArrayList<Person>> {
}

    @Test
    public void test2() {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person(1, "li"));
        personList.add(new Person(2, "wang"));

        Gson gson = new Gson();
        String personListJson = gson.toJson(personList);
        System.out.println(personList);

        List list = gson.fromJson(personListJson, new PersonListType().getType());
        System.out.println(list.get(1));
    }

1.2.3 map和json的互转

    @Test
    public void test3() {
        Map<Integer, Person> personMap = new HashMap<>();
        personMap.put(1, new Person(1, "gai"));
        personMap.put(2, new Person(2, "dada"));
        Gson gson = new Gson();
        //把map集合转换成为json字符串
        String jsonString = gson.toJson(personMap);
        System.out.println(jsonString);

        Map<Integer, Person> personMap1 = gson.fromJson(jsonString, new TypeToken<HashMap<Integer, Person>>() {
        }.getType());
        System.out.println(personMap1);
        System.out.println(personMap1.get(1));
    }

2. AJAX请求

2.1 AJAX介绍

  • AJAX即"Asynchronous(异步) Javascript And XML",是指一种创建交互式网页应用的网页开发技术
  • ajax是一种浏览器通过js异步发起请求,局部更新页面的技术
  • ajax请求的局部更新,浏览器地址不会发生变化
  • 局部更新不会舍弃原来页面的内容

2.2 原生AJAX

public class AjaxServlet extends BaseServlet {
    protected void javaScriptAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("Ajax请求过来了");

        Person person = new Person(1,"gai");
        //json格式的字符串
        Gson gson = new Gson();
        String jsonString = gson.toJson(person);
        resp.getWriter().write(jsonString);
    }
}
<!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中方法
        function ajaxRequest() {
// 				1、我们首先要创建XMLHttpRequest 
            var xmlHttpRequest = new XMLHttpRequest();
// 				2、调用open方法设置请求参数
            xmlHttpRequest.open("GET", "http://localhost:8080/16_json_ajax_i18n/ajaxServlet?action=javaScriptAjax", true);
// 				4、在send方法前绑定onreadystatechange事件,处理请求完成后的操作。
            xmlHttpRequest.onreadystatechange = function () {
                if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
                    var jsonObj = JSON.parse(xmlHttpRequest.responseText);
                    document.getElementById("div01").innerHTML = "编号" + jsonObj.id + "姓名" + jsonObj.name;
                }
            }
// 				3、调用send方法发送请求
            xmlHttpRequest.send();
        }
    </script>
</head>
<body>
<button onclick="ajaxRequest()">ajax request</button>
<div id="div01">
</div>
<table>
    <tr>
        <td>1</td>
        <td>2</td>
    </tr>
</table>
</body>
</html>

2.3 jQuery中的AJAX请求

  • $.ajax方法
参数说明
url表示请求的地址
type表示请求的类型GET或POST请求
data表示发送给服务器的数据,格式有两种:name=value&name=value;{key:value}
success请求成功,响应的回调函数
dataType响应的数据类型,常用text,xml,json
  • $ .get方法和$ .post方法
参数说明
url请求的url地址
data发送的地址
callback成功的回调函数
type返回的数据类型
  • $.getJSON方法
参数说明
urll发送请求地址
data发送给服务器的数据
callback成功的回调函数
  • serialize()方法可以把表单中所有表单项的内容获取到,并以name=value&name=value的形式进行拼接
<!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" src="script/jquery-1.7.2.js"></script>
    <script type="text/javascript">
        $(function () {
            // ajax请求
            $("#ajaxBtn").click(function () {
                $.ajax({
                    url: "http://localhost:8080/16_json_ajax_i18n/ajaxServlet",
                    data: "action=jQueryAjax",
                    type: "GET",
                    success: function (data) {
                        //alert("服务器返回的数据是" + data);
                        //var jsonObj = JSON.parse(data);
                        $("#msg").html("编号:" + data.id + "姓名:" + data.name);
                    },
                    dataType: "json"
                });
            });

            // 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");
            });

            // ajax--post请求
            $("#postBtn").click(function () {
                // post请求
                $.post("http://localhost:8080/16_json_ajax_i18n/ajaxServlet", "action=jQueryPost", function (data) {
                    $("#msg").html("post编号:" + data.id + "姓名:" + data.name);
                }, "json");

            });

            // ajax--getJson请求
            $("#getJSONBtn").click(function () {
                // 调用
                $.getJSON("http://localhost:8080/16_json_ajax_i18n/ajaxServlet", "action=jQueryGet", function (data) {
                    $("#msg").html("getJSON编号:" + data.id + "姓名:" + data.name);
                });
            });

            // ajax请求
            $("#submit").click(function () {
                // 把参数序列化

                $.getJSON("http://localhost:8080/16_json_ajax_i18n/ajaxServlet", "action=jQuerySerialize&" + $("#form01").serialize(), function (data) {
                    $("#msg").html("jQuerySerialize:" + data.id + "姓名:" + data.name);
                });
            });
        });
    </script>
</head>
<body>
<div>
    <button id="ajaxBtn">$.ajax请求</button>
    <button id="getBtn">$.get请求</button>
    <button id="postBtn">$.post请求</button>
    <button id="getJSONBtn">$.getJSON请求</button>
</div>
<div id="msg">

</div>
<br/><br/>
<form id="form01">
    用户名:<input name="username" type="text"/><br/>
    密码:<input name="password" type="password"/><br/>
    下拉单选:<select name="single">
    <option value="Single">Single</option>
    <option value="Single2">Single2</option>
</select><br/>
    下拉多选:
    <select name="multiple" multiple="multiple">
        <option selected="selected" value="Multiple">Multiple</option>
        <option value="Multiple2">Multiple2</option>
        <option selected="selected" value="Multiple3">Multiple3</option>
    </select><br/>
    复选:
    <input type="checkbox" name="check" value="check1"/> check1
    <input type="checkbox" name="check" value="check2" checked="checked"/> check2<br/>
    单选:
    <input type="radio" name="radio" value="radio1" checked="checked"/> radio1
    <input type="radio" name="radio" value="radio2"/> radio2<br/>
</form>
<button id="submit">提交--serialize()</button>
</body>
</html>

3. i18n国际化

3.1 简介

  • 国际化指同一个网站可以支持多种不同的语言,以方便不同国家访问
  • 国家化Internationalization,由于拼写过长,简单的写法就是i18n

3.2 三要素

三要素

3.3 国际化properties测试

public class I18NTest {
    @Test
    public void testLocale() {
        //获取系统默认的语言,国家信息
        Locale locale = Locale.getDefault();
        System.out.println(locale);
    }

    @Test
    public void testI18n() {
        Locale locale = Locale.CHINA;
        //通过指定的basename和locale对象读取相应的配置文件
        ResourceBundle bundle = ResourceBundle.getBundle("i18n", locale);
        System.out.println(bundle.getString("username"));
        System.out.println(bundle.getString("password"));
    }
}

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 = 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 colspan="2" align="center">
                    <input type="reset" value="<%=i18n.getString("reset")%>"/>&nbsp;&nbsp;
                    <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标签库实现国际化

<%@ 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信息
2.使用标签设置baseName
3.使用标签输出国际化信息
--%>
<fmt:setLocale value="${param.locale}"/>
<fmt:setBundle basename="i18n"/>

<a href="i18n.jsp?locale=zh_CN">中文</a>|
<a href="i18n.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 colspan="2" align="center">
                    <input type="reset" value="<fmt:message key="reset"/>"/>&nbsp;&nbsp;
                    <input type="submit" value="<fmt:message key="submit"/>"/></td>
            </tr>
        </form>
    </table>
    <br/> <br/> <br/> <br/>
</center>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在现如今这个互联网以及信息技术飞速发展的时代,信息技术被广泛地运用于人们的日常生活与生产中,并有效地提高了办事、办公效率。教育信息化的高速发展,使得学校在线考试系统,作为一种新的考试管理工具,在各大院校及相关教育机构的运用日趋普遍。绝大多数的考试机构需要不断地推进自身信息化的建设,而在考务管理方面,以往手工记账、登记信息的方式,已经逐渐不能满足现如今大数据量、高效率完成的要求,使用学校在线考试系统,对学校及相关教育机构的考试事宜管理已成当下教育信息化发展的必要手段。现代化的考试机构都应该进行学校在线考试系统的替换工作,学校在线考试系统一经推出,便在考试机构范围内引起了极大地反响。 本次学校在线考试系统的实现过程,它的开发使用B/S结构即浏览器和服务器结构框架,采用SSM框架技术,数据库使用了mysql数据库,页面设计采用了MVC框架,后端采用了SSM框架技术scrip等其他一些脚本语言,使用到在大学里面学的软件工程导论课程、mysql数据库、数据库原理、SSM框架技术高级程序设计等方面的知识完成本系统。本文结合全流程网站系统开发过程,详细介绍了此次学校在线考试系统的设计理念、模型结构,将所学知识融入到本网站的开发实践中,简略介绍了研究的背景和系统存在的现实意义,开发使用的技术背景,并对系统概要设计、系统实现与系统测试等进行了详细的介绍。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值