Servlet+Ajax交互基础案例以及Axios简化请求方式简单解析

目录

一、创建webapp项目

二、创建基础静态Ajax案例

三、创建动态交互Ajax案例 

四、实战应用:用户注册

五、 Axios

六、Axios别名


 

一、创建webapp项目

使用maven创建基础webapp模板项目即可

pom.xml依赖和插件

<dependencies>
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      <scope>provided</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet/jsp-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/taglibs/standard -->
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.30</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.10</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.annotation</groupId>
      <artifactId>javax.annotation-api</artifactId>
      <version>1.2</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
      </plugin>
    </plugins>
  </build>

 

二、创建基础静态Ajax案例

<script>
    //创建核心对象
    var xhttp;
    if (window.XMLHttpRequest){
        xhttp=new XMLHttpRequest();
    }else {
        xhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    //发送请求
    xhttp.open("GET","/ajaxdemo/ajax1.html");
    xhttp.send();
    //获取响应
    xhttp.onreadystatechange=function (){
        if (this.readyState==4 && this.status==200){
           alert(this.responseText);
        }
    };
</script>

1、在这个案例中if-else用来对不同的的浏览器获取ajax对象

2、发送请求部分

        open()用来设置请求方式以及链接,可以是资源目录,也可以是完整的http链接

        send()用来发送请求,当请求方式为post的时候这里被用来放参数

xhttp.send("username=zhangsan&password=lisi");

3、获取响应

        这里的readyState、status都是响应状态码,保证正确响应数据的前提下进行处理。

        将获取到的响应信息作为文本被弹出来

 

 4、演示

这就是一个简单的异步加载,控制台内可以看到类型是xhr。

 

 

 

 

三、创建动态交互Ajax案例 

        1、创建servlet,添加以下代码。

@WebServlet("/ajaxservlet")
public class AjaxServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String a = req.getParameter("a");
        String b = req.getParameter("b");
        resp.getWriter().write(a+" "+b);
    }
}

                doPost的作用是将处理交给doGet处理,因为都是HttpServlet对象,不是原生的,方法都封装好了,可以直接处理,

                req.getParameter("a")获取传过来的参数,get、post都可以,直接用名字就行,官方都封装好了,

                resp.getWriter().write(a+" "+b);写入响应数据
 

         2、创建前端网页

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    //创建核心对象
    var xhttp;
    if (window.XMLHttpRequest){
        xhttp=new XMLHttpRequest();
    }else {
        xhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    //发送请求
    xhttp.open("post","/ajaxdemo/ajaxservlet");
    //设置post请求头
    xhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    xhttp.send("a=Ajax&b=hello");
    //获取响应
    xhttp.onreadystatechange=function (){
        if (this.readyState==4 && this.status==200){
            alert(this.responseText);
        }
    };
</script>
</body>
</html>

        1、open设置访问路径

        2、setRequestHeader设置响应头

        3、send提交post请求参数 a=Ajax b=hello

        4、回调函数弹出响应内容,我们设置的是返回a和b两个参数

 

3、效果 

 

四、实战应用:用户注册

移出输入框自动检查数据是否合法 

1、创建前端页面

        1)创建输入框

        2)创建错误提示并隐藏

        3)为输入框绑定失去焦点事件

        4)事件向后端请求数据用户名是否存在

(用户查询过于复杂,我们设置后端固定返回)

        5)事件判断,对错误提示取消隐藏or隐藏

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form>
  名字:<input type="text" name="username" id="username">
  <span id="username_err" style="display: none">用户名含有违禁词或已存在</span>
</form>
<script>
  //绑定失去焦点事件
  document.getElementById("username").onblur=function() {
      //获取参数值
    var username = this.value;
      //发送ajax请求

      //创建核心对象
      var xhttp;
      if (window.XMLHttpRequest){
        xhttp=new XMLHttpRequest();
      }else {
        xhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      //发送请求
      xhttp.open("post","http://localhost:8080/ajaxdemo/selectUser");
      xhttp.send(username);
      //获取相应
      xhttp.onreadystatechange=function (){
        if (this.readyState==4 && this.status==200){
            if(this.responseText=="true"){
              //用户名存在,显示提示信息
                console.info(this.responseText);
              document.getElementById("username_err").style.display="";
            }else {
              // 用户名不存在,清除提示信息
              document.getElementById("username_err").style.display="none";
            }
        }
      };

  };

</script>
</body>
</html>

2、创建后端页面

        1)接受用户名

        2)判断是否存在(过于复杂,演示制作了固定返回),存在返回true,html获取到true后将错误提示的”隐藏“属性删除。

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

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接受用户名
        String username = req.getParameter("username");

        //调用查询用户名
        boolean flag = true;

        //响应标记
        resp.getWriter().write(""+flag);
    }
}

3、演示

失去焦点后

 

 

五、 Axios

 Axios 是一个基于 promise 的网络请求库,可以用于浏览器和 node.js
Axios 使用简单,包尺寸小且提供了易于扩展的接口。

官网:Axios 中文文档 | Axios 中文网 | Axios 是一个基于 promise 的网络请求库,可以用于浏览器和 node.js

 

 使用准备

需要在前端引入Axios的js文件

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

 创建后端页面


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

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        //接受请求参数
        String username = req.getParameter("username");
        //响应请求
        resp.getWriter().write(username+"hello Axios");
    }
}

创建前端页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
   axios({
     method:"post",
       url:"http://localhost:8080/ajaxdemo/axios",
       data :"username=zhangsan"
   }).then(function (response){
       alert(response.data);
   })
</script>
</body>
</html>

访问:

 

六、Axios别名

 别名方式更加简单,但是会降低阅读性。

将上面的前端改为

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
  // axios({
  //   method:"post",
  //     url:"http://localhost:8080/ajaxdemo/axios",
  //     data :"username=zhangsan"
  // }).then(function (response){
  //     alert(response.data);
  // })
  
  axios.post("/ajaxdemo/axios","username=zhangsan").then(function (response) {
      //回调函数
      alert(response.data);
  })
</script>
</body>
</html>

演示:

​​

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值