【网络编程】Servlet的前后端练习 | 表白墙 | 前后端交互 | 提交消息 | 获取消息

文章目录


一、Servlet的前后端练习

1.表白墙

服务器要实现的逻辑:

1.页面加载时,网页要从服务器这里获取到当前表白的数据。(让网页端给服务器发起http请求,服务器返回响应里就带着这些数据)

2.点击提交的时候,网页把用户输入的信息,发送到服务器这边,服务器负责保存

服务器要给页面提供两个http的接口:

1.获取消息 :

​ 网页加载的时候,给服务器发起一个ajax请求

	请求:GET/message
	响应:HTTP/1.1 200 OK
	Content-Type:application/json
	[
		{
			from:'张三',
			to:'李四',
			message:'我喜欢你'
		},
		{
			from:'A',
			to:'B',
			message:'我不喜欢你'
		}		
	]

1.客户端先发起一个ajax请求

js 复制代码
    //直接在script中写的代码会在页面加载时被执行
    //发起get请求,从服务器获取数据
    $.ajax({
        type : 'get',
        url:'message',
        //get请求不需要body,也就不需要contentType和data
        success:function(body){
            //处理服务器返回的响应数据(json格式的数组)
            
        }
    })

2.服务器收到这个请求,处理请求并进行响应

java 复制代码
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setStatus(200);
        resp.setContentType("application/json;charset-utf8");
        //setStatus和setContentType必须在getWriter之前。
        //jackson本身支持把list类型的数据,转换成json数组
        String respJson = objectMapper.writeValueAsString(messageList);
        resp.getWriter().write(respJson);
    }

3.客户端收到响应,针对响应数据进行解析处理,把响应的信息构造成页面元素(html片段),并显示出来

js 复制代码
        success:function(body){
            //处理服务器返回的响应数据(json格式的数组)
            //响应中,header带有content-Type:application/json。jquery就会自动把json字符串解析成json对象
            //如果没有带content-Type:application/json.就需要通过js代码:JSON.parse()方法来手动把json字符串转成json对象
            let container = document.querySelector('.container')
            for(let i=0;i<body.length;i++){
                //body返回的是一个数组,此时message就是获取到的一个json对象
                let message = body[i]

                //根据message信息构造html片段
                let div = document.createElement('div');
                div.className = 'div1';
                div.innerHTML = message.from+"对"+message.to+"说"+message.message;
                container.appendChild(div);
            }
        }
2.提交消息:

​ 用户点击提交的时候,ajax给服务器发起一个请求。目的是为了把用户输入的内容,发送到服务器

	请求:POST/message
	Content-Type:application/json
		{
			from:'张三',
			to:'李四',
			message:'我喜欢你'
		}
	响应:HTTP/1.1 200 OK

1.ajax给服务器发送请求

js 复制代码
        let body = { 
            "from":from,
            "to":to,
            "message":message 
        }
        //body是一个js对象,需要转换成json字符串
        let jsonString = JSON.stringify(body);
        //4.把用户填写的内容,发送给服务器,让服务器来保存
        $.ajax({
            type:'post',
            url:'message',
            contentType:'application/json;charset=utf8',
            data:jsonString,
            success:function(body){
                //收到响应之后要执行的代码
            }
        })
  • 前端ajax的url路径,不需要/,后端进行处理时,要带上 /

2.服务器读取请求,并计算出响应

java 复制代码
class Message {
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Message{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}

@WebServlet("/message")
//要和发送的请求路径一致
public class MessageServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    private List<Message> messageList = new ArrayList<>();

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

        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        //1.读取数据
        System.out.println("请求中的数据" + message);
        //2.进行保存
        messageList.add(message);
        //3.返回响应
        resp.setStatus(200);
        resp.getWriter().write("ok");
    }

3.前端代码,处理服务器的响应。

js 复制代码
            success:function(responseBody){
                //success回调函数,不是立即执行的,而是在浏览器返回成功的响应后,才会执行
                //此处的body是响应中body的内容
                console.log("responseBody:"+responseBody)
            }
完整前端代码:
html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 引入jquery -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>

<body>

    <div class="container">
        <h1>表白墙</h1>
        <p>请输入相关信息,点击提交数据会显示在表格中</p>
        <div class="div1">
            <span>谁:</span>
            <input  type="text" class="edit">
        </div>
        <div class="div1">
            <span>对谁:</span>
            <input type="text" class="edit">
        </div>
        <div class="div1">
            <span>说:</span>
            <input type="text" class="edit">
        </div>
        <div class="div1">
            <input type="button" value="提交" class="submit" onclick="Submit()">
        </div>

    </div>
</body>
<style>
    *{
        margin: 0px;
        padding: 0px;
    }
    .container{
        width: 400px;
        margin:  auto;
    }
    h1{
        text-align: center;
        margin-bottom: 40px;
    }
    p{
        text-align: center;
        color: gray;
        line-height: 60px;
    }
    .div1{
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .edit{
        margin-bottom: 20px;
        width: 200px;
        height: 30px;
    }
    span{
        width: 50px;
        margin-bottom: 20px;
    }
    .submit{
        background-color: goldenrod;
        color: white;
        width: 260px;
        height: 30px;
        border: none;
        border-radius: 5px;

    }
    .submit:active{
        background-color: gray;
    }

</style>
<script>
    function Submit(){
        let edits = document.querySelectorAll('.edit')
        console.dir(edits)
        let from = edits[0].value
        let to =edits[1].value
        let message = edits[2].value
        if(from==''||to==""||message==''){
            return
        }
       // 1.获取三个输入框的值
       console.log(from+""+to+''+message)
        let div = document.createElement('div')
        //2.构造div
        div.className='div1'
        div.innerHTML=from+"对"+to+"说"+message
        console.log(div)
        let container = document.querySelector('.container')
        container.appendChild(div)
        //3.清空文本框
        for(let input of edits){
            input.value=''
        }
        let requestBody = { 
            "from":from,
            "to":to,
            "message":message 
        }
        //body是一个js对象,需要转换成json字符串
        let jsonString = JSON.stringify(requestBody);//(这个body是发送请求的body)
        //4.把用户填写的内容,发送给服务器,让服务器来保存
        $.ajax({
            type:'post',
            url:'message',
            contentType:'application/json;charset=utf8',
            data:jsonString,
            success:function(responseBody){
                //success回调函数,不是立即执行的,而是在浏览器返回成功的响应后,才会执行
                //此处的body是响应中body的内容
                console.log("responseBody:"+responseBody)
            }
        })

    }
    //直接在script中写的代码会在页面加载时被执行
    //发起get请求,从服务器获取数据
    $.ajax({
        type : 'get',
        url:'message',
        //get请求不需要body,也就不需要contentType和data
        success:function(body){
            //处理服务器返回的响应数据(json格式的数组)
            //响应中,header带有content-Type:application/json。jquery就会自动把json字符串解析成json对象
            //如果没有带content-Type:application/json.就需要通过js代码:JSON.parse()方法来手动把json字符串转成json对象
            let container = document.querySelector('.container')
            for(let i=0;i<body.length;i++){
                //body返回的是一个数组,此时message就是获取到的一个json对象
                let message = body[i]

                //根据message信息构造html片段
                let div = document.createElement('div');
                div.className = 'div1';
                div.innerHTML = message.from+"对"+message.to+"说"+message.message;
                container.appendChild(div);
            }
        }
    })
</script>


</html>

完整后端代码:
java 复制代码
import com.fasterxml.jackson.databind.ObjectMapper;
import sun.net.httpserver.HttpServerImpl;

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;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lenovo
 * Author: Weng-Jiaming
 * Date: 2024-05-10
 * Time: 15:56
 */

class Message {
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Message{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}

@WebServlet("/message")
//要和发送的请求路径一致
public class MessageServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    private List<Message> messageList = new ArrayList<>();

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

        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        //1.读取数据
        System.out.println("请求中的数据" + message);
        //2.进行保存
        messageList.add(message);
        //3.返回响应
        resp.setStatus(200);
        resp.getWriter().write("ok");
//        resp.setContentType("application/json");
//        resp.getWriter().write("{ok:true}");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setStatus(200);
        resp.setContentType("application/json;charset=utf8");
        //setStatus和setContentType必须在getWriter之前。
        //jackson本身支持把list类型的数据,转换成json数组
        String respJson = objectMapper.writeValueAsString(messageList);
        resp.getWriter().write(respJson);
    }
}

点击移步博客主页,欢迎光临~

相关推荐
2401_872514973 分钟前
PPTP、L2TP、SSTP协议和HTTP、SOCKS5代理:全面解析与对比
网络
不烦下雨c34 分钟前
【网络】传输层协议TCP
网络·网络协议·tcp/ip
稳联技术37 分钟前
汽车焊机数据通信:Profinet转Canopen网关的神奇连接
服务器·网络·汽车
KookeeyLena52 小时前
IP池对数据爬取工作的帮助
网络·网络协议·tcp/ip
Reuuse2 小时前
【HCIA-Datacom】华为VRP系统
服务器·网络·华为
我的运维人生2 小时前
利用Python与Ansible实现高效网络配置管理
网络·python·ansible·运维开发·技术共享
PM大明同学3 小时前
Axure PR 9 标签 设计&交互
交互·axure·photoshop
启明云端wireless-tag4 小时前
设备稳定流畅视频体验,乐鑫ESP32-S3芯片方案无线音视频传输通信
物联网·音视频·交互·乐鑫·wifi模组
车载诊断技术5 小时前
电子电气架构——中央计算的软件定义汽车架构
网络·架构·汽车·soa·电子电器架构
活老鬼5 小时前
Web与HTTP
网络·网络协议·http