JavaWeb(4) - Ajax(代替了JSP页面,超级重点)
文章目录
Ajax 综述
- 异步的 JavaScript 和 XML。
- 【作用】:与服务器进行数据交换,通过AJAX请求可以给服务器发送请求,并获取服务器响应的数据;异步交互,可以在不重复加载整个页面的情况下,与服务器交换数据并更新部分网页的技术
- 同步与异步的区别:
Ajax 环境搭建
- 编写 AjaxServlet,并使用response输出字符串
@WebServlet("/ajaxServlet") public class AjaxServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.响应数据 response.getWriter().write("hello,ajax"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request,response); } }
- 在 webapp 文件夹下创建 01-ajax-demo1.html 添加以下 javascript 代码
- 创建 XMLHttpRequest 对象:用于和服务器交换数据
var xhttp; if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
- 向服务器发送请求
xhttp.open("GET", "http://localhost:8080/ajax-demo/ajaxServlet"); xhttp.send();
- 获取服务器响应数据
xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { alert(this.responseText); } };
经典例子:使用AJAX验证用户名是否存在
-
需求:在完成用户注册时,当用户名输入框失去焦点时,校验用户名是否在数据库已存在
-
编写后台逻辑代码
@WebServlet("/selectUserServlet") public class SelectUserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.接收用户名 String username = request.getParameter("username"); //2.调用service查询User对象 boolean flag = true; //3.响应标记 response.getWriter().write(""+flag); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request,response); } }
-
编写前端页面交互代码
//1.给用户名输入框绑定失去焦点事件 document.getElementById("username").onblur = function () { //2.发送ajax请求 //获取用户名的值 var username = this.value; //2.1 创建核心对象 var xhttp; if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } //2.2 发送请求 xhttp.open("GET", "http://localhost:8080/ajax-demo/selectUserServlet?username="+username); xhttp.send(); //2.3 获取访问 xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { //alert(this.responseText); //判断 if(this.responseText == "true"){ //用户名信息,显示提示信息 document.getElementById("username_err").style.display = ""; }else{ //用户名不存在,清除提示信息 document.getElementById("username_err").style.display = "none"; } } }; }
Axios 异步框架(简化开发)
基本使用
-
引入 axios 的 js 文件
<script src="js/axios-0.18.0.js"></script>
-
使用 axios 发送请求,并获取响应结果
axios({ method:"get", url:"http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan" }).then(function (resp) { alert(resp.data); })
axios({ method:"post", url:"http://localhost:8080/ajax-demo/axiosServlet" data:"username=zhangsan" }).then(function (resp){ alert(resp.data); })
请求方式别名
为了方便起见,Axios已经为所有支持的请求方法提供了别名,如:
-
发送 get 请求
axios.get("http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan").then(function(resp){ alert(resp.data); });
-
发送 post 请求
axios.post("http://localhost:8080/ajax-demo/axiosServlet","username=zhangsan").then(function(resp){ alert(resp.data); });
JSON 格式
JavaScript 对象表示法,由于语法简单,层次结构鲜明,现多用于作为数据载体,在网络中进行数据传输;
JSON数据和对象转换
- 请求数据:JSON字符串转为Java对象;
- 响应数据:Java对象转为JSON字符串;
JSON数据 <-> Java对象转换 API
- Fastjson是阿里巴巴提供的一个Java语言编写的高性能功能完善的JSON库
- 基本使用:
导入坐标
Java对象<->JSON<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.76</version> </dependency>
public class FastJsonDemo { public static void main(String[] args) { //1.将Java对象转换为JSON字符串 User user = new User(); user.setId(1); user.setUsername("zhangsan"); user.setPassword("123"); String jsonString = JSON.toJSONString(user);//{"id":1,"password":"123","username":"zhangsan"} System.out.println(jsonString); //2.将JSON字符串转为Java对象 User u = JSON.parseObject("{\"id\":1,\"password\":\"123\",\"username\":\"zhangsan\"}", User.class); System.out.println(u); } }