自学内容网 自学内容网

Servlet测试1

通过按钮提交get,post请求,并且后端响应数据,显示到前端

当点击get按钮时

是发起Get请求

后端接收到Get请求后,把数据写入到body内

当点击pst按钮时

是发起Post请求

后端接收到Post请求后,把数据写入到body内

之后前端就从body内读取数据,写入,显示到页面上

前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

    <!-- 用来接收后端的数据 -->
    <div class="connter"></div>

    <!-- 触发get post请求按钮 -->
    <button class="Get">GET</button>
    <button class="Post">POST</button>

<body>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script>
        let get=document.querySelector('.Get');
        get.onclick=function(){
            $.ajax({
                type:'get',
                url:'Demo',
                // 后端传来的数据都在body中
                success: function(body){
                    //写入数据
                    let connter=document.querySelector('.connter');
                    connter.innerHTML=body;
                }
            });
        }
        let post=document.querySelector('.Post');
        post.onclick=function(){
            $.ajax({
                type:'post',
                url:'Demo',
                success:function(body){
                    let connter=document.querySelector('.connter');
                    connter.innerHTML=body;
                }
            });
        }
    </script>
</body>
</html>

后端代码

package Demo;

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("/Demo")
public class Demo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf8");
        //当接收到get请求时,响应数据
        resp.getWriter().write("Get请求");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf8");
        //收到post请求,响应数据
        resp.getWriter().write("Post请求");
    }
}

测试1只需要知道客户端是如何发起请求的,服务器如何响应数据的即可


原文地址:https://blog.csdn.net/weixin_57535054/article/details/137729383

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!