《Java自学180天笔记》
AJAX概念
1.概念:ASynchronous JavaScript And XML 异步的JavaScript和XML
2.实现方式
<html lang="en"><head> <meta charset="UTF-8"> <title>Titletitle> <script> //定义方法 function fun() { //发送异步请求 //1.创建核心对象 var xmlhttp; if(window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); }else{ xmlhttp = new ActiveXObject("Microsoft.XMLHttp"); } //2.发送请求 /* 参数: 1.请求方式:GET、POST 2.请求的URL: 3.同步或异步请求:true(异步)或false(同步) */ xmlhttp.open("GET","ajaxServlet?username=tom",true); //3.发送请求 xmlhttp.send(); }script>head><body> <input type="button" value="发送异步请求" onclick="fun();">body>html>
package cn.itcast.web;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("/ajaxServlet")public class AjaxServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1.获取请求参数 String username = req.getParameter("username"); //2.打印username System.out.println(username); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); }}
json概念
java对象转换JSON
1.使用步骤:
1.1.导入jackson的相关jar包
1.2.创建jackson核心对象objectmapper
1.3.调用objectMapper的相关方法进行转换
package cn.itcast.web;public class Person { private int age; private String name; private String gender; public int getAge() { return age; } public void setAge(int age) { this.age = age; } 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; } @Override public String toString() { return "Person{" + "age=" + age + ", name='" + name + '\'' + ", gender='" + gender + '\'' + '}'; }}
package cn.itcast.web;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;import org.junit.Test;public class JacksonTest { //Java对象转为JSON字符串 @Test public void test1() throws Exception { //1.创建Person对象 Person p = new Person(); p.setName("张三"); p.setAge(23); p.setGender("男"); //2.创建Jackson的核心对象 ObjectMapper ObjectMapper mapper = new ObjectMapper(); //3.转换 String json = mapper.writeValueAsString(p); System.out.println(json); }}
{"age":23,"name":"张三","gender":"男"}