theme: channing-cyan
“This is the 22nd day of my participation in the First Challenge 2022. For details: First Challenge 2022”
A, JSON
1, define,
JSON (JavaScript Object Notation) is a lightweight data interchange format. It is based on a subset of ECMAScript (the JS specification of the European Computer Association) and uses a text format that is completely independent of the programming language to store and represent data. The simplicity and clarity of the hierarchy make JSON an ideal data exchange language. Easy to read and write, but also easy to machine parsing and generation, and effectively improve the efficiency of network transmission.
2, format
JSON is a formatted string. Any of the supported types can be represented by JSON, such as strings, numbers, objects, arrays, and so on. But objects and arrays are special and commonly used types. Here are the rules:
-
Mappings are indicated by colons (:). Name “: value, standard format name in double quotation marks;
-
The types that element values can have: String, bumber, Object, True, arry, true, false, null
-
Parallel data are separated by commas (“, “). Name 1: value 1, Name 2: value 2;
-
The collection of maps (objects) is represented by curly braces (” {} “). {” Name 1 “: value 1,” Name 2 “: value 2}
-
Collections (arrays) of parallel data are represented by square brackets (” [] “). As follows:
[
{” Name 1 “: value,” Name 2 “: value 2}, {” Name 1″ : value, “name 2” : value 2}
]
JSON in JavaScript
1. Represents JSON
In the webapp/jq_02/01. Json. HTML
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>Id 1 name zs age 18 var json1 = '{"id":1,"name":" ZS ","age":18}'; // write JSON, Id 1 name ZS age 18 ID 2 name ls age 19 var json2 = '[{"id":1,"name":" ZS ","age":18}, {"id":2,"name":"ls","age":19}]'; / / write JSON, Id 1 name ZS age 18 Department ID 5 name Development dept. var json3 = '{" ID ":1, "name":" ZS ", "age":18, "dept":{"id":5, "dept":{"id": 1, "name":" age":18, "dept":{"id":5, "Name ":" development department "}}'; var jsObj1 = {"id":1, "name":"zs", "age":18}; Var jsObj2 = {id:1, name:"zs", age:18}; // JS object console.log(json1.name); // undefined console.log(jsObj1.name); // zs console.log(jsObj2.name); // zs</script>
</head>
<body>
</body>
</html>
Copy the code
2, JSON and JS object conversion
The browser environment provides a utility class called JSON that provides methods to convert JSON to JS objects. Then add the following code to the script tag of the page above
// If the server response data is in JSON format, how to obtain the specific data? Parse (json1).age); // There is one way to cut strings, which is not desirable // Another way, JSON is the browser environment provides a tool, which provides methods to convert the two // JSON string to JS object console.log(json.parse (json1).age); console.log(JSON.parse(json2)); console.log(JSON.parse(json3).dept.name); Console. log(json.stringify (jsObj2)); var json4 = "{'id':1,'name':'zs','age':18}"; Parse (json4)); // Error format JSON console.log(json.parse (json4)); / / an errorCopy the code
JSON in Java
1. Represents JSON
Create a new test class, JsonTest, that demonstrates representing JSON in Java.
package cn.json;
public class JsonTest {
@Test
public void testJson(a) {
String jsonStr = "{\" ID \ :1,\"name\ :\" Development Department \",\"sn\":\"DEV\"}"; }}Copy the code
2, JSON and Java object conversion
In development, some third-party JSON operation dependencies or JAR packages are used to complete the conversion between Java objects and JSON strings. In Java, there are many dependencies or jars for converting JSON. Here are just two common ones:
- Jackson: It has built-in support in Spring MVC, which is fast and stable.
- Fastjson: Ali produced, known as the Java field in the conversion of JSON is the fastest plug-in, Chinese documentation is relatively complete.
3, Jackson
3.1. Add dependencies
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> The < version > 2.9.6 < / version > < / dependency >Copy the code
3.2. API use
package cn.json;
public class JsonTest {
@Test
public void testJackson(a) throws Exception {
Department department = new Department();
department.setId(1L);
department.setName(Development department);
department.setSn("DEV");
ObjectMapper objectMapper = new ObjectMapper();
// Java object to JSON
System.out.println(objectMapper.writeValueAsString(department));
// JSON to Java object
System.out.println(objectMapper.readValue("{\" ID \ :1,\"name\ :\" Development Department \",\"sn\":\"DEV\"}", Department.class)); }}Copy the code
4, Fastjson
4.1. Add dependencies
Alibaba </groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency>Copy the code
4.2 API use
package cn.json;
public class JsonTest {
@Test
public void testFastjson(a) {
Department department = new Department();
department.setId(1L);
department.setName(Development department);
department.setSn("DEV");
// Java object to JSON
System.out.println(JSON.toJSONString(department));
// JSON to Java object
System.out.println(JSON.parseObject("{\" ID \ :1,\"name\ :\" Development Department \",\"sn\":\"DEV\"}", Department.class)); }}Copy the code
Spring MVC response JSON
1. Respond to JSON using the Servlet API
For example, JSON data like response type {“success”:true,” MSG “:”2020-03-16 10:00”}.
1.1. Create a JsonResult class
package cn.wolfcode.qo;
@Setter
@Getter
public class JsonResult {
private boolean success;
private String msg;
}
Copy the code
1.2. Create a JsonController class
package cn.wolfcode.web.controller;
@Controller
public class JsonController {
// If the parameter has type response, the method return value can be void
@RequestMapping("/getTime")
public void getTime(HttpServletResponse response) throws Exception {
// Respond to the HTML content back to the browser
/* response.setContentType("text/html; charset=utf-8"); PrintWriter writer = response.getWriter(); Writer. write("HTML content "); writer.flush(); * /
// Respond with JSON content back to the browser
response.setContentType("application/json; charset=utf-8");
PrintWriter writer = response.getWriter();
Date now = new Date();
JsonResult jsonResult = new JsonResult();
jsonResult.setSuccess(true);
jsonResult.setMsg(now.toLocaleString());
writer.write(JSON.toJSONString(jsonResult)); // Avoid concatenating strings yourselfwriter.flush(); }}Copy the code
2. Spring MVC responds to JSON steps
- Add the Jackson dependency in pom.xml.
- Configure the MVC annotation parser in mVC.xml. Define a class that provides corresponding properties to encapsulate data.
- Attach the @responseBody annotation to the controller handling method that responds to JSON data and returns the class defined above.
- Create an object of the class defined above in the processing method and wrap the data back.
3, practice
3.1 Exercise 1
JSON data {“success”:true,” MSG “:”2020-03-16 10:00”}
Append a handler to the JsonController class
package cn.web.controller;
@Controller
public class JsonController {
@RequestMapping("/getTime")
@ResponseBody
public JsonResult getTime(a) {
Date now = new Date();
JsonResult jsonResult = new JsonResult();
jsonResult.setSuccess(true);
jsonResult.setMsg(now.toLocaleString());
returnjsonResult; }}Copy the code
3.2 exercise 2
Response type multiple departments list the JSON data, such as [{” id “: 1,” name “:” development “, “sn” : “DEV”}, {” id “: 2,” name “:” human resources “, “sn” : “HR”}]. Append a handler to the JsonController class
package cn.web.controller;
@Controller
public class JsonController {
@Autowired
private IDepartmentService departmentService;
@RequestMapping("/depts")
@ResponseBody
public List<Department> getDepts(a){
returndepartmentService.listAll(); }}Copy the code
An overview of AJAX
1. Introduction to AJAX
- AJAX is not a specific technology, but a combination of several technologies. Javascript, XHTML and CSS, DOM, XML, and XMLHttpRequest.
- The core of AJAX is simply to call a class called XMLHttpRequest in Javascript that can interact with a Web server using HTTP instead of making a request through the browser, Instead, you use this special JavaScript object to send the request and receive the response.
- XMLHttpRequest objects are commonly known on the web as AJAX objects.
2. AJAX features
After a page is displayed in the browser, the page has not changed since then. All the operation requests are issued by the Javascript code in the page, and all the results are accepted and added to the page by the Javascript code. The page displayed in the browser window is always the original page. Enhance user experience: the user can browse the web page at the same time with the server for asynchronous interaction and local update of web content.
Synchronous and asynchronous interactions:
- Sync: submit the request –> wait for the server to process it –> return the client browser cannot do anything during this time. Synchronization refers to the communication mode in which the sender sends data and the receiver sends a response before sending the next data packet.
- Asynchronous: The request is triggered by an event –> server processing (while the browser can still do other things) –> complete. Asynchronism refers to the communication mode in which the sender sends data and then sends the next data packet without waiting for the receiver to send back the response.
3. AJAX flaws
- AJAX makes heavy use of Javascript and AJAX engines, depending on browser support. Internet explorer 5.0 and later, Mozilla1.0, NetScape7 and later. Mozilla supports AJAX, but does not provide XMLHttpRequest in the same way. So, programs that use AJAX must test for compatibility across browsers.
- AJAX updates the content of the page without refreshing the entire page, so the back of the page is disabled; Some users are often confused about whether the current data is old or has been updated. This requires an obvious reminder to the user that the data has been updated.
- Streaming media support is not as good as Flash and Java applets.
- AJAX does not support cross-domain access
A simple introduction to AJAX – getting the time on the server
1, the train of thought
- Write a page, and the page has a button;
- Bind a click event handler to the button;
- Trigger the click event to send an AJAX request to the controller;
- Controller response time to the client JSON data, standard format, easy to value;
- The client receives the response and displays the time.
2. Code implementation
- Create AJAX objects (send requests and receive responses);
- Set HTTP request mode, URL, and asynchron for AJAX objects;
- Set the AJAX object to a state-listening function (a callback) that is executed when the readyState of the AJAX object changes;
- Send the request.
AJAX API in jQuery
1, the jQuery ajax ([options])
2, jQuery. Get (url, [data], [callback], [type])
3, jQuery. Post (url, [data], [callback], [type])
Eight, to practice
1. The GET request checks whether the user name exists
1.1 front-end JS code
Create webApp /jq_02/02.check_username. HTML and use jQuery to send AJAX requests
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/ static/jQuery - 1.11 / jQuery - 1.11.3. Min. Js." "></script>
<script>
$(function () {$('#username').blur(function () {
// console.log(this); // this is the event source
var username = $(this).val(); // Get the user name entered by the user
// Concatenate the parameter string
var paramString = 'username=' + username;
$.get('/checkUsername.do', paramString, function (data) {$('#result').html(data.msg)
.css('color', data.success ? 'green' : 'red'); })}); });</script>
</head>
<body>
<span id="result"></span><br/>User name:<input type="text" name="username" id="username">
</body>
</html>
Copy the code
1.2. Back-end Java code
Append a handler to the JsonController class that responds to the JSON string using Spring MVC.
package cn.web.controller;
@Controller
public class JsonController {
{"success":false," MSG ":" username registered "}
{"success":true," MSG ":" congratulations! "}
@RequestMapping("/checkUsername")
@ResponseBody
public JsonResult checkUsername(String username){
// database query to simulate lony
JsonResult jsonResult = new JsonResult();
if("lony".equals(username)){
jsonResult.setSuccess(false);
jsonResult.setMsg("User name registered");
}else {
jsonResult.setSuccess(true);
jsonResult.setMsg("Congratulations on being in the hole.");
}
returnjsonResult; }}Copy the code
2. POST requests the user to log in
2.1 front-end JS code
Create a new WebApp /jq_02/03.login. HTML and use jQuery to send AJAX requests
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The login</title>
<script src="/ static/jQuery - 1.11 / jQuery - 1.11.3. Min. Js." "></script>
<script>
$(function () {$('#login').click(function () {
/ / send AJAX
// The user name and password are obtained
var $usernameInput = $('#username');
var $passwordInput =$('#password');
var u = $usernameInput.val();
var p = $passwordInput.val();
var param = {username : u, password : p}; // Form the JS object as followsRequested parametersconsole.log(param);
$.post('/loginJson.do', param, function (data) {
console.log(data);
if(data.success){ // Login succeeded
// Send the request through JS code
// Change the address in the address bar and send the request to http://www.baidu.com
location.href = 'http://www.baidu.com';
}else{ // Login failed
$('#result').html(data.msg)
.css('color'.'red'); }}); }); });</script>
</head>
<body>
<span id="result"></span><br/>User name:<input type="text" name="username" id="username">Password:<input type="text" name="password" id="password">
<button id="login">The login</button>
</body>
</html>
Copy the code
2.2. Back-end Java code
Append a handler to the JsonController class that responds to the JSON string using Spring MVC.
package cn.web.controller; @controller public class JsonController {// If login is successful {"success":true," MSG ":" login is successful "} // If login fails {"success":false," MSG ":" login failed "} @requestMapping ("/loginJson") @responseBody public JsonResult checkUsername(String username, String password){ Assume that the data store only contains user lony password 123 JsonResult JsonResult = new JsonResult(); if("lony".equals(username) && "123".equals(password)){ jsonResult.setSuccess(true); Jsonresult. setMsg(" login succeeded "); }else { jsonResult.setSuccess(false); Jsonresult. setMsg(" login failed "); } return jsonResult; }}Copy the code
3. Secondary linkage
3.1 Practical application of secondary linkage
For example, users register to fill in the address information will use the secondary linkage. When shopping, the selection of the region will also use the secondary linkage. But three linkage is only one more level, the approach is the same.
3.2 The realization idea of secondary linkage
- After the page is loaded, the province drop-down box obtains the province data from the background;
- Render the response data obtained in the background to the drop-down box of provinces;
- Bind the event of changing value to the lower box of the province. After the value changes, the selected province ID is sent to the background.
- Render the response data obtained in the background into the city drop down box.
3.3 code implementation
3.3.1. Write pages
Create a new webApp /jq_02/04.province_city. HTML, add jQuery, provide the province and city drop-down box
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The secondary linkage</title>
<script src="/ static/jQuery - 1.11 / jQuery - 1.11.3. Min. Js." "></script>
</head>
<body>Provinces:<select id="p">
<option value="1">Please select a</option>
</select>City:<select id="c">
<option value="1">Please select a</option>
</select>
</body>
</html>
Copy the code
3.3.2. Write JS code
Use jQuery to send AJAX requests to get province and city data. Add the following code to introduce jQuery above:
<script>
$(function () {
var $p = $('#p');
var $c = $('#c');
// When the page is loaded, send an AJAX request to retrieve the province data
$.get('/provinces.do'.function (data) {
// Iterate over the province array
data.forEach(function (value) {
$p.append('<option value="' + value.id + '" >' + value.name +
'</option>');
});
});
// Bind a value change event handler to the province drop-down box. When the province drop-down box option changes, send a request to obtain the provinceCorresponding to the city data, get the data and then use DOM to display the city drop-down box $p.change(function () {
var pid = $(this).val(); // Gets the value attribute for the option of the selected province drop-down boxValue, which is the province ID value// Clear the old child elements
$c.empty();
$c.append('');
if(pid >= 1) {
$.get('/cities.do'.'pid=' + pid, function (data) {
// Walk through the city array
data.forEach(function (value) {
console.log(value);
$c.append('<option value="' + value.id + '" >' +
value.name + '</option>'); }); }); }}); });</script>
Copy the code
3.3.3. Write background to obtain provincial data and urban data
The type and City classes are used to encapsulate data to JSON and avoid manually stitching JSON
package cn.domain;
/ / provinces
public class Province {
private Long id;
private String name;
public Province(a) {}public Province(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId(a) {
return id;
}
public String getName(a) {
return name;
}
// Get all provinces
public static List<Province> getAllProvince(a) {
List<Province> provinces = new ArrayList<Province>();
provinces.add(new Province(1L."Hunan"));
provinces.add(new Province(2L."Guangdong"));
provinces.add(new Province(3L."Hubei"));
return provinces;
}
public String toString(a) {
return "Province [id=" + id + ", name=" + name + "]"; }}Copy the code
package cn.domain;
/ / the city
public class City {
private Long id;
private String name;
public City(a) {}public City(Long id, String name) {
this.id = id;
this.name = name;
}
/** * select * from city where province id = 1; *@return* /
public static List<City> getCityByProvinceId(Long pid) {
List<City> citys = new ArrayList<City>();
if (pid == 1) {
citys = Arrays.asList(
new City(11L."Changsha"),
new City(12L.Zhuzhou City),
new City(13L.Xiangtan City),
new City(14L."Hengyang city"),
new City(15L."Shaoyang"),
new City(16L."Yueyang"),
new City(17L."Changde"),
new City(18L."Zhangjiajie")); }else if (pid == 2) {
citys = Arrays.asList(
new City(21L."Guangzhou"),
new City(22L.Shenzhen City),
new City(23L."Foshan"),
new City(24L."Zhongshan"),
new City(25L."Zhuhai"),
new City(26L.Shantou City),
new City(27L."Chaozhou"),
new City(28L."Dongguan")); }else if (pid == 3) {
citys = Arrays.asList(
new City(31L.Xiaogan City),
new City(32L."Huanggang"),
new City(33L."Xianning City"),
new City(34L.Enshi Prefecture),
new City(35L."Ezhou"),
new City(36L.Wuhan City),
new City(37L."Jingmen"),
new City(38L."Xiangyang")); }return citys;
}
public Long getId(a) {
return id;
}
public String getName(a) {
return name;
}
public String toString(a) {
return "City [id=" + id + ", name=" + name + "]"; }}Copy the code
Append two processing methods to the JsonController class, using Spring MVC to respond to province and city data in JSON format.
package cn.web.controller;
@Controller
public class JsonController {
// Get JSON data for the province
@RequestMapping("/provinces")
@ResponseBody
public List<Province> getPovinces(a){
List<Province> provinces = Province.getAllProvince();
return provinces;
}
// Get JSON data for city of corresponding province
@RequestMapping("/cities")
@ResponseBody
public List<City> getPovinces(Long pid){
returnCity.getCityByProvinceId(pid); }}Copy the code