• 【JavaEE】Servlet实战案例:表白墙网页实现


    一、功能展示

    输入信息:
    在这里插入图片描述
    点击提交:
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

    二、设计要点

    2.1 明确前后端交互接口

    🚓接口一:当用户打开页面的时候需要从服务器加载已经提交过的表白数据
    在这里插入图片描述

    🚓接口二:当用户新增一个表白的时候,就把数据提交给服务器,让服务器持久化保存

    在这里插入图片描述

    2.2 使用顺序表存表白信息

    在这里插入图片描述

    2.3 doGet方法

    构造doGet方法的目的是"获取所有留言消息"
    在这里插入图片描述

    2.4 doPost方法

    构造doPost方法的目的是"提交新消息"
    在这里插入图片描述

    2.5 前端构造GET请求(显示所有信息)

    在这里插入图片描述

    2.6 前端构造POST请求(提交)

    在这里插入图片描述

    2.7 优化:使用MySQl存表白信息

    在这里插入图片描述

    在这里插入图片描述
    在这里插入图片描述

    三、完整代码实现

    3.1 项目目录

    在这里插入图片描述

    3.2 MessageServlet.java

    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
    
    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 javax.sql.DataSource;
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    
    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 messageList = new ArrayList<>();
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            // 通过这个方法来处理 "获取所有留言消息"
            // 需要返回一个 json 字符串数组. jackson 直接帮我们处理好了格式.
            List<Message> messageList = load();
            String respString = objectMapper.writeValueAsString(messageList);
            resp.setContentType("application/json; charset=utf8");
            resp.getWriter().write(respString);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            // 通过这个方法来处理 "提交新消息"
            Message message = objectMapper.readValue(req.getInputStream(), Message.class);
            save(message);
    //        messageList.add(message);
            System.out.println("消息提交成功! message=" + message);
    
            // 响应只是返回 200 报文. body 为空. 此时不需要额外处理. 默认就是返回 200 的.
        }
    
        // 这个方法用来往数据库中存一条记录
        private void save(Message message) {
            DataSource dataSource = new MysqlDataSource();
            ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/test_1?characterEncoding=utf8&useSSL=false");
            ((MysqlDataSource)dataSource).setUser("root");
            ((MysqlDataSource)dataSource).setPassword("20030603");
    
            try {
                Connection connection = dataSource.getConnection();
                String sql = "insert into message values(?, ?, ?)";
                PreparedStatement statement = connection.prepareStatement(sql);
                statement.setString(1, message.from);
                statement.setString(2, message.to);
                statement.setString(3, message.message);
                statement.executeUpdate();
    
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    
        // 这个方法用来从数据库查询所有记录
        private List<Message> load() {
            List<Message> messageList = new ArrayList<>();
    
            DataSource dataSource = new MysqlDataSource();
            ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/test_1?characterEncoding=utf8&useSSL=false");
            ((MysqlDataSource)dataSource).setUser("root");
            ((MysqlDataSource)dataSource).setPassword("20030603");
    
            try {
                Connection connection = dataSource.getConnection();
                String sql = "select * from message";
                PreparedStatement statement = connection.prepareStatement(sql);
                ResultSet resultSet = statement.executeQuery();
    
                while (resultSet.next()) {
                    Message message = new Message();
                    message.from = resultSet.getString("from");
                    message.to = resultSet.getString("to");
                    message.message = resultSet.getString("message");
                    messageList.add(message);
                }
    
                resultSet.close();
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return messageList;
        }
    
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116

    3.3 messageWall.html

    DOCTYPE html>
    <html lang="cn">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>表白墙title>
        
        <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">script>
        <style>
            /* * 通配符选择器, 是选中页面所有元素 */
            * {
                /* 消除浏览器的默认样式. */
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
    
            .container {
                width: 600px;
                margin: 20px auto;
            }
    
            h1 {
                text-align: center;
            }
    
            p {
                text-align: center;
                color: #666;
                margin: 20px 0;
            }
    
            .row {
                /* 开启弹性布局 */
                display: flex;
                height: 40px;
                /* 水平方向居中 */
                justify-content: center;
                /* 垂直方向居中 */
                align-items: center;
            }
    
            .row span {
                width: 80px;
            }
    
            .row input {
                width: 200px;
                height: 30px;
            }
    
            .row button {
                width: 280px;
                height: 30px;
                color: white;
                background-color: orange;
                /* 去掉边框 */
                border: none;
                border-radius: 5px;
            }
    
            /* 点击的时候有个反馈 */
            .row button:active {
                background-color: grey;
            }
        style>
    head>
    <body>
    <div class="container">
        <h1>表白墙h1>
        <p>输入内容后点击提交, 信息会显示到下方表格中p>
        <div class="row">
            <span>谁: span>
            <input type="text">
        div>
        <div class="row">
            <span>对谁: span>
            <input type="text">
        div>
        <div class="row">
            <span>说: span>
            <input type="text">
        div>
        <div class="row">
            <button id="submit">提交button>
        div>
        <div class="row">
            <button id="revert">撤销button>
        div>
        
    div>
    
    <script>
            // 实现提交操作. 点击提交按钮, 就能够把用户输入的内容提交到页面上显示.
            // 点击的时候, 获取到三个输入框中的文本内容
            // 创建一个新的 div.row 把内容构造到这个 div 中即可.
            let containerDiv = document.querySelector('.container');
            let inputs = document.querySelectorAll('input');
            let button = document.querySelector('#submit');
            button.onclick = function() {
                // 1. 获取到三个输入框的内容
                let from = inputs[0].value;
                let to = inputs[1].value;
                let msg = inputs[2].value;
                if (from == '' || to == '' || msg == '') {
                    return;
                }
                // 2. 构造新 div
                let rowDiv = document.createElement('div');
                rowDiv.className = 'row message';
                rowDiv.innerHTML = from + ' 对 ' + to + ' 说: ' + msg;
                containerDiv.appendChild(rowDiv);
                // 3. 清空之前的输入框内容
                for (let input of inputs) {
                    input.value = '';
                }
                // 4. 通过 ajax 构造 post 请求, 把这个新的消息提交给服务器.
                let body = {
                    "from": from,
                    "to": to,
                    "message": msg
                };
                $.ajax({
                    type: 'post',
                    url: 'message',
                    contentType: "application/json;charset=utf8",
                    data: JSON.stringify(body),
                    success: function(body) {
                        // 这是响应成功返回之后, 要调用的回调.
                        console.log("消息发送给服务器成功!");
                    }
                });
            }
            let revertButton = document.querySelector('#revert');
            revertButton.onclick = function() {
                // 删除最后一条消息.
                // 选中所有的 row, 找出最后一个 row, 然后进行删除
                let rows = document.querySelectorAll('.message');
                if (rows == null || rows.length == 0) {
                    return;
                }
                containerDiv.removeChild(rows[rows.length - 1]);
            }
    
            // 在页面加载的时候, 希望能够从服务器获取到所有的消息, 并显示在网页中.
            $.ajax({
                type: 'get',
                url: 'message',  // url 都是使用相对路径的写法. 相对路径意味着工作路径就是当前文件所在的路径.
                                 // 当前文件所在路径是 /message_wall/ , 因此此时构造的请求就是 /message_wall/message
                success: function(body) {
                    // body 是收到的响应的正文部分. 如我们之前的约定, body 应该是 json 数组
                    // 由于响应的 Content-Type 是 application/json, 此时收到的 body 会被 jquery 自动的把它从 字符串
                    // 转成 js 对象数组. 此处就不需要手动的进行 JSON.parse 了.
                    // 此处的 body 已经是一个 JSON.parse 之后得到的 js 对象数组了.
                    // 就需要遍历这个 body 数组, 取出每个元素, 再依据这样的元素构造出 html 标签, 并添加到页面上.
                    let container = document.querySelector('.container');
                    for (let message of body) {
                        let rowDiv = document.createElement('div');
                        rowDiv.className = "row";
                        rowDiv.innerHTML = message.from + " 对 " + message.to + " 说: " + message.message;
                        container.appendChild(rowDiv);
                    }
                }
            });
        script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170

    3.4 pom.xml

    
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0modelVersion>
    
        <groupId>org.examplegroupId>
        <artifactId>message_wallartifactId>
        <version>1.0-SNAPSHOTversion>
    
        <properties>
            <maven.compiler.source>8maven.compiler.source>
            <maven.compiler.target>8maven.compiler.target>
        properties>
    
        <dependencies>
            
            <dependency>
                <groupId>com.fasterxml.jackson.coregroupId>
                <artifactId>jackson-databindartifactId>
                <version>2.15.0version>
            dependency>
    
            
            <dependency>
                <groupId>javax.servletgroupId>
                <artifactId>javax.servlet-apiartifactId>
                <version>3.1.0version>
                <scope>providedscope>
            dependency>
    
            
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <version>5.1.49version>
            dependency>
    
    
        dependencies>
    
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    3.5 web.xml

    DOCTYPE web-app PUBLIC
            "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
            "http://java.sun.com/dtd/web-app_2_3.dtd" >
    
    <web-app>
        <display-name>Archetype Created Web Applicationdisplay-name>
    web-app>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
  • 相关阅读:
    我们用STM32开发时为什么要使用架构
    ESP8266跟ESP-01S区别
    中断(全网最细!)
    【Python 趣味习题】
    vue-事件修饰符
    PyQt5学习笔记--摄像头实时视频展示、多线程处理、视频编解码
    适用于嵌入式单片机的差分升级通用库+详细教程
    数据结构与算法【红黑树】的Java实现+图解
    centos 部署java环境,拷贝jar包并运行
    linux常见指令
  • 原文地址:https://blog.csdn.net/m0_68101404/article/details/134420901