Time: 2024-04-08 14:21:19
Author: Jackasher
Ajax-2
今天学的是,基于JSON格式的数据交换,浏览器自带JSON对象,JSON对象可以调用方法把字符串转为JSON对象,从而可以以JS中的属性访问方式访问
| 12
 
 | _String = ajax.responseTextvar jsonObject = JSON.parse(_String)
 
 | 
如果需要连接数据库,我们需要把数据库的信息封装成对象,然后使用阿里巴巴提供的fastjson转化成JSON格式的字符串
| 12
 
 | String _String = JSON.toJSONString(_Object)our.print(_String)
 
 | 
总体来说是这样
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 
 | package com.example.ajax;
 import com.alibaba.fastjson2.JSON;
 import jakarta.servlet.ServletException;
 import jakarta.servlet.annotation.WebServlet;
 import jakarta.servlet.http.HttpServlet;
 import jakarta.servlet.http.HttpServletRequest;
 import jakarta.servlet.http.HttpServletResponse;
 import org.junit.Test;
 
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.sql.*;
 import java.util.ArrayList;
 import java.util.List;
 
 @WebServlet("/request3")
 public class Servlet4 extends HttpServlet {
 
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 List<User> users = new ArrayList<>();
 User jack = new User("jack","casio233.");
 users.add(jack);
 
 
 PrintWriter out = resp.getWriter();
 
 try {
 Class.forName("com.mysql.cj.jdbc.Driver");
 } catch (ClassNotFoundException e) {
 throw new RuntimeException(e);
 }
 
 try (Connection root = DriverManager.getConnection("jdbc:mysql://localhost:3306/jack", "root", "casio233.");) {
 Statement statement = root.createStatement();
 
 String sql = "select * from users";
 ResultSet resultSet = statement.executeQuery(sql);
 while(resultSet.next()){
 String username = resultSet.getString("username");
 String password = resultSet.getString("password");
 users.add(new User(username, password));
 }
 String jsonString = JSON.toJSONString(users);
 out.print(jsonString);
 } catch (SQLException e) {
 throw new RuntimeException(e);
 }
 
 
 }
 }
 
 
 |