【JavaWeb】JSON&AJAX&i18n

JSON是一种轻量级数据交换格式,易于人们阅读和编写,同时也易于机器解析和生成
JSON采用完全独立于语言的文本格式
很多语言都提供了对JSON的支持(c,c++,java等),使得JSON成为理想的数据交换格式
轻量级指的是跟xml作比较
数据交换指的是客户端服务器之间业务数据传递格式

一.JSON的使用

1.在JavaScript中的使用

  • json的定义
    json是由键值对组成,并由花括号包围,每个键由引号引起来,键和值之间使用冒号进行分隔,多组键值对之间用逗号进行分隔
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        //json的定义
    var jsonobj = {
    
    
        "key1" : 12,
        "key2" : "abc",
        "key3" : true,
        "key4" : [11,"arr",false],
        "key5" : {
    
    
            "key5_1" : 551,
            "key5_2" : "123"
        },
        "key6" : [{
    
    
            "key6_1_1" : 666,
            "key6_1_2" : "666"
        },{
    
    
            "key6_2_1" : 111,
            "key6_2_2" : "111"
        }]
    };
    alert(typeof(jsonobj));//object json就是一个对象
    </script>
</head>
  • json的访问
    (1).json本身是一个对象
    (2).json中的key我们可以理解为是对象中的一个属性
    (3).json中的key访问就跟访问对象的属性一样 —— json对象.key
         alert(jsonobj.key1);
          for(var i = 0;i < jsonobj.key4.length;i++){
    
    
              alert(jsonobj.key4[i]);
          }
         alert(jsonobj.key5.key5_1);
        var jsonItem = jsonobj.key6[0];
        alert(jsonItem.key6_1_1);
        var jsonItem = jsonobj.key6[1];
        alert(jsonItem.key6_2_1);
  • json的两个常用方法
    json的存在有两种形式:对象(称为json对象)和字符串(称为json字符串)
    JSON.stringify() 把json对象转换成为json字符串
    JSON.parse() 把json字符串转换成为json对象
    一般我们要操作json中的数据的时候,需要json对象的格式
    一般我们要在客户端和服务器之间进行数据交换的时候,使用json字符串
 var jsonobjstring = JSON.stringify(jsonobj);
       alert(jsonobjstring);
        var jsonobj2 = JSON.parse(jsonobjstring);
        alert(jsonobj2.key1);

2.在java中的使用

  • javaBean和json的互转
 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);
        //fromJson把json字符串转换成为java对象
        //第一个参数是json字符串
        //第二个参数是转换回去的java对象类型
        Person person1 = gson.fromJson(personJsonString,Person.class);

        System.out.println(person1);

    }
  • List和json的互转
public void test2(){
    
    

    List<Person> personList = new ArrayList<>();

    personList.add(new Person(1,"雪碧"));
    personList.add(new Person(2,"可乐"));

    Gson gson = new Gson();

    String personListJsonString = gson.toJson(personList);

    System.out.println(personListJsonString);

    List<Person> list = gson.fromJson(personListJsonString, new PersonListType().getType());

    System.out.println(list);

    }
  • map和json的互转
 public void test3(){
    
    

            Map<Integer,Person> personMap = new HashMap<>();

            personMap.put(1,new Person(1,"芬达"));
            personMap.put(2,new Person(2,"芬达"));

            Gson gson = new Gson();

            String personMapJsonString = gson.toJson(personMap);

            System.out.println(personMapJsonString);

           // Map<Integer,Person> personMap2  = gson.fromJson(personMapJsonString, new PersonMapType().getType());

            Map<Integer,Person> personMap2  = gson.fromJson(personMapJsonString, new TypeToken<HashMap<Integer,Person>>(){
    
    }.getType());

            System.out.println(personMap2);

            Person p = personMap2.get(1);

            System.out.println(p);

        }

二.AJAX请求

1.AJAX请求

  • AJAX(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术
  • AJAX是一种浏览器通过js异步发起请求,局部更新页面的技术
  • AJAX请求的局部更新,浏览器地址栏不会发生变化,局部更新不会舍弃原来页面的内容
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type = "text/javascript">
          //在这里使用javaScript语言发起Ajax请求,访问服务器AjaxServlet中doGet
          function ajaxRequest(){
    
    

            //1.我们首先要创建XMLHttpRequest

            var xmlhttprequest = new XMLHttpRequest();

            //2.调用open方法设置请求参数

            xmlhttprequest.open("GET","http://localhost:8080/16_json_ajax_i18n/ajaxServlet?action=doGet",true);

            //3.在send方法前绑定onreadystatechange事件,处理请求完成后的操做

              xmlhttprequest.onreadystatechange = function(){
    
    
                  //4表示:请求完成,响应就绪
                  //200表示ok
                  if(xmlhttprequest.readyState == 4 && xmlhttprequest.status == 200){
    
    

                      var jsonObj = JSON.parse(xmlhttprequest.responseText);

                      //把响应的数据显示在页面上
                    document.getElementById("div01").innerHTML = "编号:" + jsonObj.id + ",姓名:" + jsonObj.name;

                   //   document.getElementById("div01").innerHTML = xmlhttprequest.responseText;
                  }

              }

                //4.调用send方法发送请求

                xmlhttprequest.send();

        }
    </script>
</head>
<body>
<button onclick="ajaxRequest()">ajax request</button>
<div id="div01">
</div>
</body>
</html>
public class AjaxServlet extends HttpServlet {
    
    


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    

        req.setCharacterEncoding("UTF-8");

        resp.setContentType("text/html;charset=UTF-8");

        System.out.println("Ajax请求过来了");

        Person person = new Person(1, "中国");

        Gson gson = new Gson();

        String personJsonString = gson.toJson(person);

        resp.getWriter().write(personJsonString);
    }
}

2.原生AJAX请求实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type = "text/javascript">
          //在这里使用javaScript语言发起Ajax请求,访问服务器AjaxServlet中doGet
          function ajaxRequest(){
    
    

            //1.我们首先要创建XMLHttpRequest

            var xmlhttprequest = new XMLHttpRequest();

            //2.调用open方法设置请求参数
              //true代表异步
              // false代表同步
            xmlhttprequest.open("GET","http://localhost:8080/16_json_ajax_i18n/ajaxServlet?action=doGet",true);

            //3.在send方法前绑定onreadystatechange事件,处理请求完成后的操做

              xmlhttprequest.onreadystatechange = function(){
    
    
                  //4表示:请求完成,响应就绪
                  //200表示ok
                  if(xmlhttprequest.readyState == 4 && xmlhttprequest.status == 200){
    
    

                      var jsonObj = JSON.parse(xmlhttprequest.responseText);

                      //把响应的数据显示在页面上
                    document.getElementById("div01").innerHTML = "编号:" + jsonObj.id + ",姓名:" + jsonObj.name;

                   //   document.getElementById("div01").innerHTML = xmlhttprequest.responseText;
                  }

              }

                //4.调用send方法发送请求

                xmlhttprequest.send();

              alert("我是最后一行代码");

        }
    </script>
</head>
<body>
<button onclick="ajaxRequest()">ajax request</button>
<a href="http://localhost:8080/16_json_ajax_i18n/ajaxServlet?action=doGet">非ajax请求</a>
<div id="div01">
</div>
<table border="1">
    <tr>
        <td>1.1</td>
        <td>1.2</td>
    </tr>
<tr>
    <td>2.1</td>
    <td>2.2</td>
</tr>
</table>
</body>
</html>

在这里插入图片描述

3.jQuery中的AJAX请求

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="script/jquery-3.6.1.min.js"></script>
    <script type="text/javascript">
  $(function(){
    
    

      //ajax请求
      $("#ajaxBtn").click(function() {
    
    
          $.ajax({
    
    

              url:"http://localhost:8080/16_json_ajax_i18n/ajaxServlet",
              data:"action=doGet",
              type:"GET",
              success: function (data) {
    
    
                  //alert("服务器返回的数据是: " + data);

                  var jsonObj = JSON.parse(data);

                  $("#msg").html("编号: " + jsonObj.id + " , 姓名: " + jsonObj.name);
              },
              dataType: "text"

          });


      });


  });

    </script>
</head>
<body>
<button id="ajaxBtn">$.ajax请求</button>
<div id="msg">

</div>
</body>
</html>
public class AjaxServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    


           req.setCharacterEncoding("UTF-8");

            resp.setContentType("text/html;charset=UTF-8");

            System.out.println("doGet == 方法调用了 ");

             Person person = new Person(1, "中国");

             try {
    
    

                 Thread.sleep(3000);

             } catch (InterruptedException e) {
    
    
                 e.printStackTrace();

             }

             //JSON字符串格式
            Gson gson = new Gson();

             String personJsonString = gson.toJson(person);

            resp.getWriter().write(personJsonString);
    }

在这里插入图片描述

响应的数据类型也可以是json

  <script type="text/javascript" src="script/jquery-3.6.1.min.js"></script>
    <script type="text/javascript">
  $(function(){
    
    

      //ajax请求
      $("#ajaxBtn").click(function() {
    
    
          $.ajax({
    
    

              url:"http://localhost:8080/16_json_ajax_i18n/ajaxServlet",
              data:"action=doGet",
              type:"GET",
              success: function (data) {
    
    
                  //alert("服务器返回的数据是: " + data);

                 // var jsonObj = JSON.parse(data);

                  $("#msg").html("编号: " + data.id + " , 姓名: " + data.name);
              },
              dataType: "json"

          });


      });


  });

    </script>

$.get方法$.post方法

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

   //ajax—get请求
      $("#getBtn").click(function() {
    
    

          $.get("http://localhost:8080/16_json_ajax_i18n/ajaxServlet","action=doGet",function(data){
    
    

              $("#msg").html("编号: " + data.id + " , 姓名: " + data.name);

          },"json");

      });
      //ajax—post请求
      $("#postBtn").click(function() {
    
    

          $.post("http://localhost:8080/16_json_ajax_i18n/ajaxServlet","action=doGet",function(data){
    
    

              $("#msg").html("编号: " + data.id + " , 姓名: " + data.name);

          },"json");

      });
 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        req.setCharacterEncoding("UTF-8");

        resp.setContentType("text/html;charset=UTF-8");

        System.out.println("doGet == 方法调用了 ");

        Person person = new Person(1, "中国");

        Gson gson = new Gson();

        String personJsonString = gson.toJson(person);

        resp.getWriter().write(personJsonString);

    }
 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    

                req.setCharacterEncoding("UTF-8");

                resp.setContentType("text/html;charset=UTF-8");

                System.out.println("doGet == 方法调用了 ");

                Person person = new Person(1, "中国");

                Gson gson = new Gson();

               String personJsonString = gson.toJson(person);

                resp.getWriter().write(personJsonString);

    }

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

 //getJSON方法
      $("#getJSONBtn").click(function() {
    
    

          $.getJSON("http://localhost:8080/16_json_ajax_i18n/ajaxServlet","action=doGet",function(data){
    
    

              $("#msg").html("编号: " + data.id + " , 姓名: " + data.name);

          });

      });
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        req.setCharacterEncoding("UTF-8");

        resp.setContentType("text/html;charset=UTF-8");

        System.out.println("doGet == 方法调用了 ");

        Person person = new Person(1, "中国");

        Gson gson = new Gson();

        String personJsonString = gson.toJson(person);

        resp.getWriter().write(personJsonString);

    }

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

 //getJSON方法
      $("#submit").click(function() {
    
    

          alert($("#form01").serialize());

          $.getJSON("http://localhost:8080/16_json_ajax_i18n/ajaxServlet","action=doGet&" + $("#form01").serialize(),function(data){
    
    

              $("#msg").html("编号: " + data.id + " , 姓名: " + data.name);

          });

      });
 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        req.setCharacterEncoding("UTF-8");

        resp.setContentType("text/html;charset=UTF-8");

        System.out.println("用户名: " + req.getParameter("username"));

        System.out.println("密 码: " + req.getParameter("password"));

        System.out.println("doGet == 方法调用了 ");

        Person person = new Person(1, "中国");

        Gson gson = new Gson();

        String personJsonString = gson.toJson(person);

        resp.getWriter().write(personJsonString);

    }

三.i18n

1.概念

Internationalization -国际化,由于字符过长,简称i18n,i首字母,n尾字母,之间有18个字母,即i18n

需求:不同国家的人访问,看到的内容不同,布局一样

苹果的策略是: 为不同的国家创建不同的网站,英文http://www.apple.com,中文http://www.apple.com/cn
如果需求不大,可采用苹果这种策略

2.国际化三要素

在这里插入图片描述

3.国际化资源properties测试

  • en_US
username=username
password=password
sex=sex
age=age
  • zh_CN
username=用户名
password=密码
sex=性别
age=年龄
  • 测试
 public void testI18n(){
    
    
        //得到需要的locale对象
        Locale locale = Locale.US;
        //根据指定的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"));
    }
  • locale对象测试
 public void testLocale(){
    
    
        //获取系统默认的语言 国家信息
        Locale locale  = Locale.getDefault();
        System.out.println(locale);
        //获取所有的可使用的语言信息
    for(Locale locale1 : Locale.getAvailableLocales()){
    
    
        System.out.println(locale1);
    }
    //输出中文中国信息
       System.out.println(Locale.CHINA);
    //输出英文美国信息
       System.out.println(Locale.US);
    }

4.实现国际化

  • 通过请求头
<%@ page import="java.util.Locale" %>
<%@ page import="java.util.ResourceBundle" %><%--
  Created by IntelliJ IDEA.
  User: asus
  Date: 2022/12/15
  Time: 9:21
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <style type="text/css">
      table{
    
    margin:auto;}
      h1{
    
    text-align:center;}
    </style>
</head>
<body>
<%

    //从请求头中获取Locale信息
    Locale locale = request.getLocale();

    System.out.println(locale);

    //获取读取包(根据指定的baseName和Locale读取 语言信息)
    ResourceBundle i18n = ResourceBundle.getBundle("i18n", locale);

%>
<a href="i18n.jsp?country=cn">中文</a></br>
<a href="i18n.jsp?country=usa">英文</a>
<h1><%=i18n.getString("regist")%></h1>
<table>
<form>
        <tr>
            <td><%=i18n.getString("username")%></td>
            <td><input 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>
</body>
</html>

注意:可以在浏览器,设置,语言中,设置语言,将使用的置顶即可

  • 通过语言类型选择
<%@ page import="java.util.Locale" %>
<%@ page import="java.util.ResourceBundle" %><%--
  Created by IntelliJ IDEA.
  User: asus
  Date: 2022/12/15
  Time: 9:21
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <style type="text/css">
      table{
    
    margin:auto;}
      h1{
    
    text-align:center;}
    </style>
</head>
<body>
<%
    
    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信息
        locale = request.getLocale();

    }

    System.out.println(locale);

    //获取读取包(根据指定的baseName和Locale读取 语言信息)
    ResourceBundle i18n = ResourceBundle.getBundle("i18n", locale);

%>
<a href="i18n.jsp?country=cn">中文</a></br>
<a href="i18n.jsp?country=usa">英文</a>
<h1><%=i18n.getString("regist")%></h1>
<table>
<form>
        <tr>
            <td><%=i18n.getString("username")%></td>
            <td><input 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>
</body>
</html>

i18n中文中国properties文件

username=用户名
password=密码
sex=性别
age=年龄
regist=注册
boy=男
girl=女
email=邮箱
reset=重置
submit=提交

i18n英文美国properties文件

username=username
password=password
sex=sex
age=age
regist=regist
boy=boy
girl=girl
email=email
reset=reset
submit=submit
  • 通过JSTL标签库fmt
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<%--1.使用标签设置Locale信息--%>
<fmt:setLocale value="${param.locale}"/>
<%--2.使用标签设置baseName--%>
<fmt:setBundle basename="i18n"/>
<a href="i18n_fmt.jsp?locale=zh_CN">中文</a></br>
<a href="i18n_fmt.jsp?locale=en_US">英文</a>

<h1><fmt:message  key="regist"/></h1>
<table>
    <form>
        <tr>
            <td><fmt:message  key="username"/></td>
            <td><input 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>
</body>
</html>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_53798578/article/details/128138066