JavaWeb---JSON、AJAX、i18n

1.What is JSON?

  JSON (JavaScript Object Notation) is a lightweight data exchange format. It is easy for people to read and write. At the same time, it is easy to parse and generate by machine. JSON uses a completely language-independent text format, and many languages ​​provide support for json (including C, C++, C#, Java, JavaScript, Perl, Python, etc.). This makes JSON an ideal data exchange format.
json is a lightweight data exchange format.
Lightweight refers to comparison with xml.
Data exchange refers to the transfer format of business data between the client and the server.

1.1. The use of JSON in JavaScript.

1.1.1, the definition of json

  json is composed of key-value pairs and is surrounded by curly braces (curly braces). Each key is enclosed in quotation marks, the key and value are separated by a colon, and multiple key-value pairs are separated by commas.
Example of json definition:

var jsonObj = {
				"key1":11,
				"key2":"aaa",
				"key3":true,
				"key4":[11,"as",false],
				"key5":{
					"key5_1":51,
					"key5_2":"key5_2_value"
				},
				"key6":[{
					"key6_1":61,
					"key6_2":"key6_6_value"
				},{
					"key6_3":63,
					"key6_4":"key6_6_value"
				}]
			}

1.1.2, json access

json itself is an object.
The key in json can be understood as an attribute in the object.
The key access in json is the same as accessing the properties of the object: json object.key

json access example:

alert(typeof(jsonObj));//object类型 ,json就是一个对象
			alert(jsonObj.key1);//11
			alert(jsonObj.key3);//true
			alert(jsonObj.key4);//得到数组[11,"as",true]
			//json中数组值的遍历
			for (var i = 0; i < jsonObj.key4.length; i++) {
				alert(jsonObj.key4[i]);
			}
			alert(jsonObj.key5.key5_1);//51
			alert(jsonObj.key5.key5_2);//key5_2_value
			alert(jsonObj.key6);//得到json数组

			//取出来每一个元素都是json对象
			var jsonItem = jsonObj.key6[0];
			alert(jsonItem.key6_2);
			alert(jsonItem.key6_1);

1.1.3 Two common methods of json

There are two forms of json.

  • One is: the existence of objects in the form of objects, we call it json objects.
  • One is: it exists in the form of a string, we call it a json string.

Two forms of use cases:
Generally, when we want to manipulate the data in json, we need the format of the json object.
Generally, when we want to exchange data between the client and the server, we use json strings.
JSON.stringify(): convert json object into json string
JSON.parse(): convert json string into json object

Sample code:
Insert picture description here

1.2, the use of JSON in java

1.2.1. Conversion between javaBean and json

//1.json和javaBean的互相转化
    @Test
    public void test1(){
    
    
        Person person = new Person(1, "smlz");
        //创建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);
    }

1.2.2, List and json conversion

//2.List和Json之间的相互转化
    @Test
    public void test2(){
    
    
        List<Person> personList = new ArrayList<>();
        personList.add(new Person(1,"jack"));
        personList.add(new Person(2,"hjj"));

        Gson gson = new Gson();
        //把List转换为json字符串
        String personListJsonString = gson.toJson(personList);
        System.out.println(personListJsonString);

        //把json字符串转回List
        List<Person> list = gson.fromJson(personListJsonString, new PersonListType().getType());
        System.out.println(list);
        Person person = list.get(0);
        System.out.println(person);
    }

1.2.3, mutual conversion of map and json

//3.Map和Json之间的相互转化
    @Test
    public void test3(){
    
    
        Map<Integer,Person> personMap = new HashMap<>();
        personMap.put(1,new Person(1,"jack"));
        personMap.put(2,new Person(2,"hjj"));

        Gson gson = new Gson();
        //把Map转换为Json字符串
        String personMapJsonString = gson.toJson(personMap);
        System.out.println(personMapJsonString);

        //把Json字符串转回Map
        Map<Integer,Person> personMap1 = gson.fromJson(personMapJsonString, new TypeToken<HashMap<Integer, Person>>() {
    
    }.getType());//使用匿名内部类的形式
        System.out.println(personMap1);
        Person person = personMap1.get(1);
        System.out.println(person);
    }

2. AJAX request

2.1, what is an AJAX request

  AJAX stands for "Asynchronous Javascript And XML" (asynchronous JavaScript and XML), which refers to a web development technology for creating interactive web applications.
  Ajax is a technology in which the browser initiates a request asynchronously through js and partially updates the page.
  The partial update of Ajax request, the browser address bar will not change, and the partial update will not discard the content of the original page

2.2. Examples of native AJAX requests:

<!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/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);

						// alert(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>
	</body>
</html>

2.3, AJAX request in jQuery

$.ajax method

  • url represents the requested address
  • type indicates the type of request, GET or POST request
  • data represents the data sent to the server (there are two formats:
    one: name=value&name=value
    two: {key:value})
  • success The request is successful, the callback function of the response
  • dataType Response data type (common data types are: text means plain text, xml means xml data, json means json object)
// ajax请求
				$("#ajaxBtn").click(function(){
					
					$.ajax({
						url:"http://localhost:8080/json_ajax_i18n/ajaxServlet",
						data:"action=jQueryAjax",
						type:"GET",
						success:function (data) {
							alert("服务器返回的数据是:" + data);
							$("#msg").html("编号:" + data.id + ",姓名:" + data.name);
						},
						dataType: "json"
					});
				});

$.get 方法和$.post 方法

url: requested url address
data: sent data
callback: successful callback function
type: returned data type

Insert picture description here

$.getJSON 方法

url: the requested url address
data: the data sent to the server
callback: the successful callback function

Insert picture description here
Form serialization serialize()
serialize() can get the contents of all the form items in the form and splice them in the form of name=value&name=value.
Insert picture description here

4. Internationalization of i18n (understand the content)

4.1. What is i18n internationalization?

  Internationalization refers to the fact that the same website can support multiple different languages ​​to facilitate access by users from different countries and languages.
  Regarding internationalization, the simplest solution we think of is to create different websites for different countries, such as Apple. Its English official website is http://www.apple.com and the Chinese official website is http://www.apple .com/cn
   Apple’s solution is not suitable for all companies, and we hope that the same website can be displayed in different languages ​​according to the user’s area when different people visit it, and the layout of the website will not change. .
   So there is what we call internationalization. Generally speaking, internationalization means that people from different countries on the same website can display different languages ​​when they visit it. But in fact, this demand is not strong. Generally, companies that really have international needs still use Apple's solution to create different pages for different countries. So we can understand the content of internationalization.
  Internationalization in English, but due to the long spelling, foreigners thought of a simple wording called I18N, which represents the word Internationalization. It starts with I and ends with N, and there are 18 letters in the middle, so I18N is abbreviated. In the future, we will say that I18N and internationalization mean the same thing.

4.2 Introduction to relevant elements of internationalization

Insert picture description here

4.3, international resource properties test

Configure configuration files in two languages: i18n_en_US.properties English
Insert picture description here

i18n_zh_CN.properties Chinese
Insert picture description here

Internationalization test code:

public class I18nTest {
    
    

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

        //获取中文,中文常量的locale对象
        System.out.println(Locale.CHINA);
        //获取英文,英文常量的local对象
        System.out.println(Locale.US);
    }

    @Test
    public void testI18n(){
    
    
        //先获得我们需要的Locale对象
        Locale locale = Locale.CHINA;
        //通过指定的basename和Local对象,读取相应的配置文件
        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"));
    }
}

4.4, JSTL tag library to achieve internationalization

Insert picture description here

<%@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=""/>--%>
	<a href="i18n_fmt.jsp?locale=zh_CN">中文</a>|
	<a href="i18n_fmt.jsp?locale=en_US">english</a>
	<center>
		<h1><fmt:message key="register"/></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"/>" />&nbsp;&nbsp;
				<input type="submit" value="<fmt:message key="submit"/>" /></td>
			</tr>
			</form>
		</table>
		<br /> <br /> <br /> <br />
	</center>
</body>
</html>

Guess you like

Origin blog.csdn.net/weixin_42118981/article/details/108916134