07#.Java Web中:初步了解Vue中的Axios

Axios 是什么?

Axios 是一个基于 promise 的 HTTP 库,简单的讲就是可以发送get、post请求。说到get、post,大家应该第一时间想到的就是Jquery吧,毕竟前几年Jquery比较火的时候,大家都在用他。但是由于Vue、React等框架的出现,Jquery也不是那么吃香了。也正是Vue、React等框架的出现,促使了Axios轻量级库的出现,因为Vue等,不需要操作Dom,所以不需要引入Jquery.js了。

以上摘自:
链接:https://www.imooc.com/article/287900

   axios的github: https://github.com/axios/axios
   中文说明: https://www.kancloud.cn/yunye/axios/234845

准备工作:

  1. axios.js文件
  2. vue.js文件
  3. Json.utils工具类

1.axios的语法

  • get请求
// 为给定 ID 的 user 创建请求
axios.get('/user?id=12')
  .then(response=>{
    
    
    console.log(response);
  })
  .catch(error=>{
    
    
    console.log(error);
  });

// 可选地,上面的请求可以这样做
axios.get('/user', {
    
    
    params: {
    
    
      id: 12
    }
  })
  .then(response=>{
    
    
    console.log(response);
  })
  .catch(error=>{
    
    
    console.log(error);
  });
  • post请求
axios.post('/user', {
    
    
    id: 12,
    username:"jay"
  })
  .then(response=>{
    
    
    console.log(response);
  })
  .catch((error=>{
    
    
    console.log(error);
  });
  • axios方式(原始方式)
    在这里插入图片描述
    为方便起见,为所有支持的请求方法提供了别名
axios.get(url[, config])
axios.post(url[, data[, config]])
axios.request(config)
axios.delete(url[, config])
axios.head(url[, config])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

2.axios的使用

需求:使用axios发送异步请求给ServletDemo01,并在页面上输出内容

步骤:

  1. 创建ServletDemo01
  2. 把axios和vue导入项目 引入到页面
  3. 使用get(), post() 请求
  • html页面代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>使用axios发送异步请求</title>
    <script src="js/axios-0.18.0.js"></script>
    <script src="js/vuejs-2.5.16.js"></script>
</head>
<body>
    <div id="app">
        <!--
            目标:当页面加载的时候,发送异步请求给ServletDemo01,
            获取响应数据,展示到id为msg的div中
        -->
        <div id="msg" v-text="message"></div>
    </div>
    <script>
        var vue = new Vue({
     
     
           el:"#app",
           data:{
     
     
               message:""
           },
            created(){
     
     
                //使用axios发送异步请求,异步的get请求可以通过url地址携带数据
                /*axios.get("/demo01?id=12&username=jay").then(response =>{
                    //response就是服务器端的响应, response.data才是我们想要获取的响应体的数据
                    console.log(response.data)
                    this.message = response.data
                })*/

                //异步的get请求,还能通过json格式携带数据
                /*axios.get("/demo01",{
                    params:{
                        id:12,
                        username:"jay"
                    }
                }).then(response=>{
                    //拿到响应体的数据赋值给message
                    this.message = response.data
                })*/

                //axios发送异步的post请求,并且携带请求参数,post方式也可在url后面携带请求参数
                /*axios.post("/demo01?id=13&username=aobama").then(response=>{
                    //拿到响应体的数据赋值给message
                    this.message = response.data
                })*/

                //axios发送异步的post请求,使用json格式携带请求参数
                axios.post("/demo01",{
     
     id:14,username:"jay"}).then(response=>{
     
     
                    //拿到响应体的数据赋值给message
                    this.message = response.data
                })
            }
        });
    </script>
</body>
</html>
  • ServletDemo01的代码
package com.itheima.servlet;

import com.itheima.utils.JsonUtils;

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

@WebServlet("/demo01")
public class ServletDemo01 extends HttpServlet {
    
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
    
    
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
    
    
        //获取"name=value&name=value"类型的参数
        /*String id = request.getParameter("id");
        String username = request.getParameter("username");*/

        //获取json类型的请求参数
        Map user = JsonUtils.parseJSON2Object(request, Map.class);

        response.setContentType("text/html;charset=UTF-8");

        response.getWriter().write("你好世界:"+user.get("id")+","+user.get("username"));
    }
}

注意:

  1. get方式携带请求参数,以及post方式通过url携带请求参数,实际上携带给服务器的参数的格式是"name=value&name=value&name=value", 服务器接收到这种格式的请求参数的时候,可以使用request的getParameter(name)或者getParameterValues(name)或者getParameterMap()方法获取请求参数
  2. post方式通过json格式携带请求参数,那么提交给服务器的参数的格式是{name:value,name:value},服务器就无法通过以前的getParameter(name)等方法获取请求参数。那么服务器要通过解析json获取,我们直接使用JsonUtils.java工具类就行了

附录:

JsonUtils.java工具类

import com.alibaba.fastjson.JSON;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class JsonUtils {
    
    


    /**
     * 响应结果
     * @param response
     * @param obj
     * @throws IOException
     */
    public static void printResult(HttpServletResponse response, Object obj) throws IOException {
    
    
        response.setContentType("application/json;charset=utf-8");
        JSON.writeJSONString(response.getWriter(),obj);
    }

    /**
     * 把json转成对象
     * @param request
     * @param tClass
     * @param <T>
     * @return
     * @throws IOException
     */
    public static <T> T parseJSON2Object(HttpServletRequest request, Class<T> tClass) throws IOException{
    
    
        // 把表单数据之间转对象
        return JSON.parseObject(request.getInputStream(),tClass);
    }


}

猜你喜欢

转载自blog.csdn.net/qq_42522848/article/details/107558925