Ajax technology [Ajax actual combat] (2) - comprehensive detailed explanation (learning summary --- from entry to deepening)

 

Table of contents

Ajax in action


Ajax in action

create project

Create a Java project

 

 

 Click finish to complete the project creation, then right click and select "add Framework Support..."

 Check the options in the red box, click "OK", and the web folder will appear under the project after completion

 Click on "project structure"

 Click Modules, select the "Web" module, then click "+" as shown in the icon, follow the default path, and then click "OK"

 Configure tomcat server

 Select Edit Configuration...

 Select the Deployment tab, click the "+" on the right, select the project to be deployed, and press the default

 

 Add the war file to be deployed, set the Application context to "/", click ok.

Add dependencies

 In the "dependencies" tab, click the "+" on the right, select Library..., add Tomcat

 Continue to add other necessary dependencies according to the actual situation, such as fastjson, commonslang, etc.

 import jquery package

In the web directory, create a js folder, and put jquery-3.6.0.js in the js directory

 Create entity class User

package com.itbaizhan.ajax.pojo;
public class User {
    private Integer id;
    private String username;
    private String password;
    private Double salary;
    private String birthday;
    public Integer getId() {
        return id;
   }
    public void setId(Integer id) {
        this.id = id;
   }
    public String getUsername() { 
        return username;
   }
    public void setUsername(String username)
   {
        this.username = username;
   }
    public String getPassword() {
        return password;
   }
    public void setPassword(String password)
   {
        this.password = password;
   }
    public Double getSalary() {
        return salary;
   }
    public void setSalary(Double salary) {
        this.salary = salary;
   }
    public String getBirthday() {
        return birthday;
   }
    public void setBirthday(String birthday)
   {
        this.birthday = birthday;
 }
    public User(Integer id, String username,
    String password, Double salary, String birthday) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.salary = salary;
        this.birthday = birthday;
   }
    public User() {
   }
}

create page

Create the static section in index.jsp

<body>
    <div>
        <table align="center" width="60%" border="1">
            <tr>
                <td>ID:</td>
                <td><input type="text" name="id" id="id"/></td>
                <td>姓名:</td>
                <td><input type="text" name="username" id="username"/></td>
                <td>密码:</td>
                <td><input type="text" name="password" id="password"/></td>
            </tr>
            <tr>
                <td>收入:</td>
                <td><input type="text" name="salary" id="salary"/></td>
                <td>出生日期:</td>
                <td><input type="text" name="birthday" id="birthday"/></td>
                <td colspan="2"></td>
            </tr>
            <tr align="center">
                <td colspan="6">
                    <input type="button" value="添加用户" id="add" />
                    <input type="button" value="更新用户" id="update"/>
                </td>
            </tr>
        </table> <hr/>
        <table align="center" width="60%" bgcolor="" border="1" id="myTable">
            <thead>
            <tr align="center">
                <td>ID</td>
                <td>姓名</td>
                <td>密码</td>
                <td>收入</td>
                <td>生日</td>
                <td>操作</td>
            </tr>
        </thead>
            <tbody id="tBody"></tbody>
        </table>
    </div>
</body>

Create UserServlet

@WebServlet("/user.do")
public class UserServlet extends HttpServlet
{
 @Override
    public void init() throws ServletException {
   }
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
   }
    
     @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   }
}

Configure web.xml

<servlet>
     <servlet-name>UserServlet</servlet-name>
     <servlet-class>
        com.itbaizhan.ajax.servlet.UserServlet
     </servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>UserServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Query user list

page related

$(function () {
     //初始化用户数据
     getData();
 });
// 获取页面初始化数据
function getData(){
    $.getJSON("user.do", {flag:"getData"},function (result) {
        listUser(result);
   });
}
// 遍历数据生成数据
function listUser(obj){
    var str ="";
    $.each(obj,function(){
        str+= "<tr align='center'>" +
            "<td id='"+this.id+"'>"+this.id +"</td>"+
            "<td>"+this.username+"</td>" +
            "<td>"+this.password+"</td>" +
            "<td>"+this.salary+"</td>" +
            "<td>"+this.birthday+"</td>" +
            "<td><a href='#' onclick='preUpdateUser("+this.id+")'>更新
</a>&nbsp;&nbsp;<a href='#' onclick='deleteUser("+this.id+")'>删除 </a>
</td></tr>"
   });
    $("#tBody").prepend(str);
}

servlet-related

@Override
public void init() throws ServletException {
    ArrayList<User> list = new ArrayList<>();
    User user1 = new User(1,"zhangsan","123",2000d,"1997-09-01");
    User user2 = new User(2,"lisi","123",3000d,"1998-08-23");
    User user3 = new User(3,"zhaoliu","123",2500d,"1996-05-16");
    User user4 = new User(4,"wangwu","123",2080d,"1995-10-12");
    User user5 = new User(5,"zhengsan","123",3200d,"1999-12-20");
    User user6 = new User(6,"liugang","123",4200d,"1994-04-10");
    list.add(user1);
    list.add(user2);
    list.add(user3);
    list.add(user4);
    list.add(user5);
    list.add(user6);
    ServletContext servletContext = this.getServletContext();
    servletContext.setAttribute("list",list);
}
// 获取页面初始化数据
private void getData(HttpServletRequest req, HttpServletResponse resp) throws IOException
{
    List<User> list = (List<User>)
      this.getServletContext().getAttribute("list");
      String s = JSON.toJSONString(list);
      resp.setContentType("application/json");
      PrintWriter pw = resp.getWriter();
      pw.print(s);
      pw.flush();
      pw.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
    String flag = req.getParameter("flag");
    if("getData".equals(flag)){
        this.getData(req,resp);
   }
}

Add user

page related

//添加按钮绑定点击事件
$("#add").click(function(){
    addOrUpdateUser("addUser");
});
// 用户添加或者用户更新
function addOrUpdateUser(flag){
    // 从页面中获取数据
    var userid = $("#id").val();
    var username = $("#username").val();
    var password = $("#password").val();
    var salary = $("#salary").val();
    var birthday = $("#birthday").val();
    var data = {
        userid:userid,
        username:username,
        password:password,
        salary:salary,
        birthday:birthday,
        flag:flag
   }
    $.get("user.do",data,function(result){
        alert(result);
        location.reload();
   });
}

servlet-related

/**
     * 处理添加用户请求
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
private void addUser(HttpServletRequest req, HttpServletResponse resp) throws IOException
{
    User user = this.createUser(req);
    ServletContext servletContext = this.getServletContext();
    List<User> list = (List<User>)servletContext.getAttribute("list");
    list.add(user);
    resp.setContentType("text/plain;charset=utf-8");
    PrintWriter pw = resp.getWriter();
    pw.print("添加成功");
    pw.flush();
    pw.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
    String flag = req.getParameter("flag");
    if("getData".equals(flag)){
        this.getData(req,resp);
   }else if("addUser".equals(flag)){
        this.addUser(req,resp);
   }
}
// 获取请求数据
private User createUser(HttpServletRequest
req){
    String userid = req.getParameter("userid");
    String username = req.getParameter("username");
    String password = req.getParameter("password");
    String salary = req.getParameter("salary");
    String birthday = req.getParameter("birthday");
    User user = new User();
    user.setId(Integer.parseInt(userid));
    user.setUsername(username);
    user.setPassword(password);
    user.setSalary(Double.valueOf(salary));
    user.setBirthday(birthday);
    return user;
}

update user

page related

// 更新之前的数据选择
function preUpdateUser(userid){
    var arr = new Array();  
$("#"+userid).closest("tr").children().each(
function(index,ele){
        if(index <=4){
            arr[index]= ele.innerText
       }
   });
    $("#id").val(arr[0]);
    $("#id").attr("readonly",true);
    $("#username").val(arr[1]);
    $("#password").val(arr[2]);
    $("#salary").val(arr[3]);
    $("#birthday").val(arr[4]);
}
//更新按钮绑定点击事件
$("#update").click(function(){
 addOrUpdateUser("updateUser");
});
// 用户添加或者用户更新
function addOrUpdateUser(flag){
    // 从页面中获取数据
    var userid = $("#id").val();
    var username = $("#username").val();
    var password = $("#password").val();
    var salary = $("#salary").val();
    var birthday = $("#birthday").val();
    var data = {
        userid:userid,
        username:username,
        password:password,
        salary:salary,
        birthday:birthday,
        flag:flag
   }
    $.get("user.do",data,function(result){
       alert(result);
       location.reload();
   });
}

servlet-related

/**
     * 处理更新用户请求
     * @param req
     * @param resp
     * @throws IOException
     */
private void updateUser(HttpServletRequest req,
                        HttpServletResponse resp) throws IOException{
    User user = this.createUser(req);
    ServletContext servletContext = this.getServletContext();
    List<User> userList = (List<User>) servletContext.getAttribute("list");
    //list转map
    Map<Integer, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
    //根据id获取user
    User user1 = userMap.get(user.getId());
    //删除指定的user
    userList.remove(user1);
    //添加新的user
    userList.add(user);
    //按id排序
    userList.sort(new Comparator<User>() {
        @Override
        public int compare(User o1, User o2)
         {
            return o1.getId() - o2.getId();
       }
   });
    //输出至页面
    resp.setContentType("text/plain;charset=utf-8");
    PrintWriter pw = resp.getWriter();
    pw.print("更新成功");
    pw.flush();
    pw.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
    String flag = req.getParameter("flag");
    if("getData".equals(flag)){
        this.getData(req,resp);
   }else if("addUser".equals(flag)){
        this.addUser(req,resp);
   }else if("updateUser".equals(flag)){
        this.updateUser(req,resp);
   }
}

delete users

page related

// 删除用户
function deleteUser(userid){
    $("#"+userid).closest("tr").remove();
 $.post("user.do", {userid:userid,flag:"delete"},function(result){
        alert(result)
   })
}

servlet-related

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
    String flag = req.getParameter("flag");
    if("getData".equals(flag)){
        this.getData(req,resp);
   }else if("addUser".equals(flag)){
        this.addUser(req,resp);
   }else if("updateUser".equals(flag)){
        this.updateUser(req,resp);
   }else if("delete".equals(flag)){
        this.deleteUser(req,resp);
   }
}
/**
     * 处理删除用户请求
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
private void deleteUser(HttpServletRequest req,
                        HttpServletResponse resp) throws ServletException, IOException{
    ServletContext servletContext = this.getServletContext();
    List<User> userList = (List<User>)servletContext.getAttribute("list");
    String userid = req.getParameter("userid");
    //list转map
    Map<Integer, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
    //根据id获取user
    if(StringUtils.isNotEmpty(userid)){
        User user1 = userMap.get(Integer.parseInt(userid));
        //删除指定的user
        userList.remove(user1);
        resp.setContentType("text/plain;charset=utf-8");
        PrintWriter pw = resp.getWriter();
        pw.print("删除成功");
        pw.flush();
        pw.close();
   }else{
        resp.setContentType("text/plain;charset=utf-8");
        PrintWriter pw = resp.getWriter();
        pw.print("删除失败");
        pw.flush();
        pw.close();
   }
}

running result

review:

 Serialization and deserialization of Java objects

 What is serialization and deserialization

When two processes communicate remotely, they can send various types of data to each other. No matter what type of data, it will be transmitted on the network in the form of binary sequence. For example, we can send string information through the http protocol; we can also send Java objects directly on the network. The sender needs to convert this Java object into a byte sequence before it can be transmitted on the network; the receiver needs to restore the byte sequence into a Java object before it can be read normally. The process of converting a Java object into a sequence of bytes is called object serialization. The process of restoring a sequence of bytes to a Java object is called deserialization of the object.

 Classes and interfaces involved in serialization

ObjectOutputStream represents the object output stream, and its writeObject(Object obj) method can serialize the obj object specified by the parameter, and write the obtained byte sequence to a target output stream.

ObjectInputStream represents an object input stream, and its readObject() method reads a sequence of bytes from a source input stream, deserializes them into an object, and returns it. Only objects of classes that implement the Serializable interface can be serialized. The Serializable interface is an empty interface that only serves as a marker.

 serialize object to file

 ObjectOutputStream can serialize an in-memory Java object to a file on disk. The serialized object must implement the Serializable serialization interface, otherwise an exception will be thrown.

 create object

public class Users implements Serializable {
    private int userid;
    private String username;
    private String userage;
    public Users(int userid, String username, String userage) {
        this.userid = userid;
        this.username = username;
        this.userage = userage;
    }
    public Users() { }
    public int getUserid() {
        return userid;
   }
    public void setUserid(int userid) {
        this.userid = userid;
   }
    public String getUsername() {
        return username;
   }
    public void setUsername(String username)
   {
        this.username = username;
   }
    public String getUserage() {
        return userage;
   }
    public void setUserage(String userage) {
        this.userage = userage;
   }
    @Override
    public String toString() {
 return "Users{" +
                "userid=" + userid +
                ", username='" + username + '\'' +
                ", userage='" + userage + '\'' +
                '}';
   }

serialized object

public class TestObjectOutputStream {
    public static void main(String[] args) {
        //创建对象输出字节流与文件输出字节流对象
        try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d:/data3"))){
            //创建Users对象
            Users users = new Users(1,"Oldlu","18");
            //将对象序列化到文件中
            oos.writeObject(users);
            //刷新
            oos.flush();
       }catch(IOException e){
            e.printStackTrace();
       }
   }
}

Deserialize the object into memory

public class TestObjectInputStream {
    public static void main(String[] args) {
        //创建对象输入字节流与文件字节输入流对象
        try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:/data3"))) 
       {
            //将对象反序列化到内存中
            Users users = (Users) ois.readObject();
            System.out.println(users);
       }catch(Exception e){
            e.printStackTrace();
       }
   }
}

The role of the File class in IO

 When using a file as a data source or target, in addition to using a string as a file and specifying the location, we can also use the File class to specify.

public class TestFile {
    public static void main(String[] args) {
        //创建字符缓冲流与文件字符输入流对象
        try(BufferedReader br =  new BufferedReader(new FileReader(new File("d:/sxt.txt")));
            //创建字符输出流对象
            PrintWriter pw = new PrintWriter(new File("d:/sxt8.txt"))){
            //操作流
            String temp = "";
            int i=1;
            while((temp = br.readLine()) != null){
                pw.println(i+","+temp);
                i++;
}
            pw.flush();
       }catch(IOException e){
            e.printStackTrace();
       }
   }
}

Decorator mode to build IO flow system

Introduction to the Decorator Pattern

The decorator pattern is a commonly used pattern among the 23 design patterns of GOF. It can realize the packaging and decoration of the original class, so that the new class has stronger functions.

 decorator pattern

class Iphone {
 private String name;
 public Iphone(String name) {
     this.name = name;
}
 public void show() {
    System.out.println("我是" + name + ",可以在屏幕上显示");
  }
}
class TouyingPhone {
    public Iphone phone;
    public TouyingPhone(Iphone p) {
        this.phone = p;
 }
 // 功能更强的方法
 public void show() {
     phone.show();
     System.out.println("还可以投影,在墙壁上显示");
 }
}
public class TestDecoration {
 public static void main(String[] args) {
     Iphone phone = new Iphone("iphone30");
     phone.show();
     System.out.println("===============装饰后");
     TouyingPhone typhone = newTouyingPhone(phone);
     typhone.show();
 }
}

Decorator pattern in IO flow system

The decorator pattern is widely used in the IO flow system, which makes the flow more functional and more flexible. for example:

FileInputStream  fis = new FileInputStream(src);
BufferedInputStream  bis = new BufferedInputStream(fis);

 Obviously, BufferedInputStream decorates the original FileInputStream, so that ordinary FileInputStream also has a cache function and improves efficiency.

Guess you like

Origin blog.csdn.net/m0_58719994/article/details/131647774