笔记-JavaWeb学习之旅18

发布时间:2019-06-18 06:00:01发布者:Mr.Zhang阅读(233)

AJAX:ASynchronous JavaScript And XML 异步的JavaScript 和XML

异步和同步:客户端和服务器端相互通信的基础上

同步:客户端操作后必须等待服务器端的响应,在等待的期间客户端不能做其他操作

异步:客户端操作后,不需要等待服务器端的响应,在服务器处理请求的过程中,客户端可以进行其他的操作

JQuery对AJAX实现

实现异步的方式

使用$.ajax()发送异步请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-3.3.1.min.js"></script>
    <script>
        //定义方法
        function fun(){
            //使用JQuery的方式实现异步请求
            $.ajax({
                url:"ajaxServlet1",//必选参数
                type:"POST",//请求方式,可选参数
                data:{"username":"jack","age":23},//请求参数,可选
                success:function(data){
                    alert(data);//data变量是服务器响应给会的结果值
                },//响应成功后的回调函数,可选
                error:function(){
                    alert("出错啦...");
                },//请求响应出现错误,会执行的回调函数
               dataType:"text"//设置接受到的响应数据的格式
            });
        }
    </script>
</head>
<body>
    <input type="button" value="发送异步请求" onclick="fun();">
    <input>
</body>
</html>
package com.data.ajax;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/ajaxServlet1")
public class AjaxServlet1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求参数
       String username =  request.getParameter("username");
       String age =  request.getParameter("age");
        System.out.println(username);
       //响应请求请求
        response.getWriter().write("hello :" + username+age);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

使用$.get()和$.post()发送异步请求

$.get(url,[data],[callback],[type])

url:请求路径

data:请求参数

callback:回调函数,载入成功后执行的函数

type:响应结果的类型

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-3.3.1.min.js"></script>
    <script>
        function fun() {
            $.get("ajaxServlet1",{"username":"zhangsan"},function (data) {
                alert(data)
            })
        }
    </script>
</head>
<body>
    <input type="button" value="发送异步请求" onclick="fun();">
    <input>
</body>
</html>

$.post(url,[data],[callback],[type])

JSON:

1.概念:JavaScript Object Notation JavaScript对象表示法

json现在多用于存储和交换文本信息的语法

进行数据的传输

JSON比XML更小,更快,更易解析

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        var person1={"name":"张三",age:23,'gender':"true"};
        //遍历对象
        for(key in person1){
            alert(key+":"+person1[key]);
        }
        //获取name的值
        var name1 = person1.name;
        alert(name1)
        //嵌套格式{}->[]
        var person2 = {
            "person":[
            {"name":"张三","age":23,"gender":true},
            {"name":"李四","age":24,"gender":true},
            {"name":"王五","age":25,"gender":false},
        ]
        };
        //嵌套格式  []-{}
        var person3=[
            {"name":"张三","age":23,"gender":true},
            {"name":"李四","age":24,"gender":true},
            {"name":"王五","age":25,"gender":false},
        ]
        alert("===============")
        //遍历数组person3
        for(var i=0;i<person3.length;i++){
            var l=person3[i];
            for(key in l ){
                 alert(key+l[key]);
            }
        }
    </script>
</head>
<body>
</body>
</html>

JSON解释器--jackson

常见JSON解释器:Jsonlib,Gson,fastjson,jackson

把Java对象转换为JSON对象

注解:@JsonIgnore:排除不需要的属性,@JsonFormat:属性值格式化

复杂java对象转换

1.List:转换出来的是数组

3.Map:转换出来结果与对象格式一致

package com.data.domain;

import com.fasterxml.jackson.annotation.JsonFormat;

import java.util.Date;

public class Person {
    private String name;
    private String gender;
    private int age;
    @JsonFormat(pattern = "yyyy-MM-dd")//设置指定格式
    private Date birthday;

    public Person(String name, String gender, int age, Date birthday) {
        this.name = name;
        this.gender = gender;
        this.age = age;
        this.birthday = birthday;
    }
    public Person(String name, String gender, int age) {
        this.name = name;
        this.gender = gender;
        this.age = age;
    }

    public Person() {

    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}
package com.data.test;

import com.data.domain.Person;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.io.File;
import java.util.*;

public class TestDemo1 {
    //把Java对象转化为JSON对象
    @Test
    public void test1() throws Exception {
        Person person = new Person("张三","男",20);
        //创建Jackson的核心对象,ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
   /*
    writeValueAsString(obj):将对象转为json字符串
    转换方法:writeValue(参数1,obj):该方法有很多重载方法
    参数1:
        File:将obj对象转换为JSON字符串,并保存到指定的文件中
        Writer:将Obj对象转换为JSON字符串,并将json数据填充到字符输出流中
        OutputStream:将obj对象转换为JSON字符串,并将json数据填充到字节输出流中

   */
        String s = mapper.writeValueAsString(person);
        System.out.println(s);//{"name":"张三","gender":"男","age":20}
        //将JSON写入文件
        mapper.writeValue(new File("e://a.txt"),person);
    }
    @Test
    public void test2() throws Exception {
        Person person = new Person("张三","男",20, new Date());
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(person);
        System.out.println(s);
    }
        //List集合转JSON对象
    @Test
    public void test3() throws Exception {
        Person person1 = new Person("张三","男",20, new Date());
        Person person2 = new Person("李四","女",22, new Date());
        Person person3 = new Person("王五","男",23, new Date());
        Person person4 = new Person("赵六","女",24, new Date());
        //创建List集合
        List<Person> list = new ArrayList<>();
        list.add(person1);
        list.add(person2);
        list.add(person3);
        list.add(person4);
       //把List集合转换为JSON对象
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(list);
        System.out.println(s);
    }

    @Test
    public void test5() throws Exception {
        Map<String,Object> map = new HashMap<>();
        map.put("name","张三");
        map.put("age",22);
        map.put("gender","男");
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(map);
        System.out.println(s);
    }
    //把JSON对象转换为java对象
    @Test
    public void test6() throws Exception {
        //初始化JSON字符串
        String json = "{\"gender\":\"男\",\"name\":\"张三\",\"age\":22}";
        ObjectMapper mapper = new ObjectMapper();
        Person s = mapper.readValue(json,Person.class);
        System.out.println(s);
    }

}




本文转自博客园,原文地址:https://www.cnblogs.com/train99999/p/11042911.html