JavaWeb简易留言板 servlet+ajax+mysql

  • Post author:
  • Post category:java




使用servlet+ajax将数据存入数据库实现简易留言板

先上图~~

加载界面同时加载历史留言

加载历史留言

发表留言 字数超出限制禁用按钮

字数限制

发表留言成功~

留言成功

下面贴代码 message_board.html


<body>
<nav class="navbar navbar-default navbar-static-top">
    <div class="container-fluid">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"></button>
            <a class="navbar-brand" style="font-size: 30px;color: #fff;" href="index.html">首页</a>
        </div>
    </div>
</nav>
    <div style="width: 550px; margin: 0 auto;">
        <div class="inputMessage">
            <textarea id="textArea" rows="3" cols="70" name="msg" placeholder=" 说点什么吧!"></textarea>
            <div style="padding-bottom: 5px;">
                <input type="text" name="name" autocomplete="off" class="input-name" placeholder=" 请输入昵称">
                <button type="submit" class="btn btn-primary submitMsg">发表</button>
                <label id="limitSize">50</label><span>/</span><span>50</span>
            </div>
        </div>
        <div>
            <ul>
                <li class="li-admin">
                    <hr>
                    <div class="mname-admin">admin</div>
                    <div>大家好!文明留言,从我做起~</div>
                    <div>2019-04-01 17:02:58</div>
                    <hr>
                </li>
            </ul>
        </div>
        <div>
            <ul id="ul">

            </ul>
        </div>
    </div>
    <script src="js/jquery-2.1.0.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script>
        // 发表留言时用append插入div语句
        var comment = null;
        function div(name,msg,time) {
            comment = '<li>\n' +
                '<hr>\n' +
                '<div class="mname">' + name +
                '</div>\n' +
                '<div class="mmsg">' + msg +
                '</div>\n' +
                '<div class="mtime">' + time +
                '</div>\n' +
                '<hr>\n' +
                '</li>';
        }
        // 加载页面时调用的添加div语句的方法
        function addBox(data_display) {
            $.each(JSON.parse(data_display),function(index,obj){
                $("#ul").append('<li>\n' +
                    '<hr>\n' +
                    //获取名字
                    "<div class='mname'>"+obj['mname']+"</div>"+
                    //获取留言
                    "<div class='mmsg'>"+obj['mmsg']+"</div>"+
                    //获取留言时间
                    "<div class='mtime'>"+obj['mtime']+"</div>"+
                    '<hr>\n' +
                    "</li>");
            });
        }

        $(function () {
            // 页面加载时从数据库读取留言数据
            $.post("displayMsgServlet",function (data_display) {
                addBox(data_display);
            });

            // 设置留言最长为50个字符
            var long = $("#limitSize");
            $("#textArea").bind("input propertychange",function () {
                long.html(50 - this.value.length);
                if (this.value.length > 50) {
                    long.css("color","red");
                    // 禁用发表按钮
                    $(".submitMsg").attr("disabled",true);
                } else {
                    long.css("color","black");
                    $(".submitMsg").attr("disabled",false);
                }
            });
            // 提交留言
            $(".submitMsg").click(function () {
                var _name = $(".input-name").val();
                var _msg = $("#textArea").val();
                if (_msg != "" && _name != "") {
                    /**
                     * sensitiveWordsServlet 使用filter铭感词过滤 
                     * 并使用JDBC将昵称 过滤后的留言和 时间存入到数据库中
                     */
                    $.post("sensitiveWordsServlet", {name: _name, msg: _msg}, function (data_submit) {
                        alert("留言成功!");
                        div(data_submit.name,data_submit.msg,data_submit.time);
                        $("#ul").append(comment);
                        // 清空留言框中的内容
                        $("#textArea").val("");
                    }, "json");
                } else {
                    alert("请输入留言或昵称!请检查");
                }
            });
        });
    </script>
</body>
</html>

接着是 DisplayMsgServlet.java

package com.cangwu.msgboard;

import com.cangwu.utils.DruidUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

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

/**
 * @Author: Cangwu
 * @Date: 2019/4/7 21:17
 */
@WebServlet("/displayMsgServlet")
public class DisplayMsgServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // 查询已有留言
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        String sql = "select * from tb_msgboard";
        List<Message> messages = null;
        try {
            messages = runner.query(sql, new BeanListHandler<Message>(Message.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        ObjectMapper mapper = new ObjectMapper();
        // 将对象转为json字符串
        String json = mapper.writeValueAsString(messages);
        // 向前台输出到data_display中
        response.getWriter().write(json);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

DruidUtils.java JDBC工具类:

package com.cangwu.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @Author: Cangwu
 * @Date: 2019/4/1 22:48
 */
public class DruidUtils {

    private static DataSource ds ;

    static {
        try {
            // 加载配置文件
            Properties pro = new Properties();
            pro.load(DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            // 获取DataSource
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    /**
     * 释放资源
     */
    public static void close(Statement stmt , Connection conn) {
        close(null,stmt,conn);
    }

    public static void close(ResultSet rs, Statement stmt, Connection conn ) {

        if (rs != null ) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (stmt != null ) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null ) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取连接池的方法
     */
    public static DataSource getDataSource() {
        return ds;
    }
}

Message.java 是含有三个参数的bean文件 这里就不贴啦

private String mname;

private String mmsg;

private String mtime;



小白努力学习中 有问题欢迎指出哈!~



2021-7-22 更新

贴一个代码地址 :

https://github.com/cangwuwuwu/msgBoard


由于很早之前写的 所以没测试过是否还能正常运行了。贴个代码仅供参考



版权声明:本文为qq_43581949原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。