520 is here, teach you to make a small project of JavaWeb confession wall

content

1. Configure the Maven project

1.1 Create a Maven project

1.2 Introducing related dependencies

1.3 Overall project structure

2. Agreed front-end and back-end interaction interface

3. Server code

3.1 Create the Message class

3.2 Create tool class

3.3 Add message class (AddMessage)

3.4 Query information class (MessageList)

4. Front-end code

5. Create the database

6. Deploy the project

7. Effect display


1. Configure the Maven project

1.1 Create a Maven project

After that, select the storage path and naming, which is relatively simple, so I won't go into details!

1.2 Introducing related dependencies

Introduce servletjackson , mysql-connector and lombok dependencies in pom.xml:

<?xml version="1.0" encoding="UTF-8"?>

<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.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>message_wall</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>message_wall Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.22</version>
      <scope>provided</scope>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.13.2.1</version>
    </dependency>

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

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

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>message_wall</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

 

1.3 Overall project structure

 

2. Agreed front-end and back-end interaction interface

        The so-called "front-end and back-end interaction interface" is a key link in web development, specifically: which HTTP requests are allowed to be sent by the page to the server, and what HTTP responses are expected to be obtained for each request.

  1. Get all the information from the server
    Request: GET
    Response: JSON format
  2. Submit information to the server
    Request: JSON format
    Response: JSON format

3. Server code

3.1 Create the Message class

@Setter
@Getter
public class Message {
    private String from;
    private String to;
    private String message;

    public Message(String from, String to, String message) {
        this.from = from;
        this.to = to;
        this.message = message;
    }
}

Note: @Setter and @Getter automatically generate all get and set methods.

3.2 Create tool class

Create the DBUtils class for connecting to the database.

The DBUtil class mainly implements the following functions:

  • Create an instance of MysqlDataSource and set properties such as URL , username , password and so on.
  • Provide the getConnection method to establish a connection with the MySQL server.
  • Provides a close method to release necessary resources.
public class DBUtils {
    private DBUtils() {
    }

    private static volatile MysqlDataSource mysqlDataSource;
    private static volatile Connection connection;

    private static MysqlDataSource getMysqlDataSource() {
        if (mysqlDataSource == null) {
            synchronized (DBUtils.class) {
                if (mysqlDataSource == null) {
                    mysqlDataSource = new MysqlDataSource();
                    mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/messagewall?character=utf8&useSSL=true");
                    mysqlDataSource.setUser("root");
                    mysqlDataSource.setPassword("12345678");
                }
            }
        }
        return mysqlDataSource;
    }

    // 1.get connect
    public static Connection getConnection() {
        if (connection == null) { // 首次访问
            synchronized (DBUtils.class) {
                if (connection == null) {
                    try {
                        MysqlDataSource dataSource = getMysqlDataSource();
                        connection = (Connection) dataSource.getConnection();
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                }
            }
        }
        return connection;
    }

    // 2.提供关闭资源的方法
    public static void close(ResultSet resultSet, PreparedStatement statement) throws SQLException {
        if (resultSet != null) {
            resultSet.close();
        }
        if (statement != null) {
            statement.close();
        }
    }
}

Create the  StringUtils class for nullability:

public class StringUtils {
    public static boolean hasLength(String str) {
        return !(str == null || str.length() == 0);
    }
}

3.3 Add message class ( AddMessage )

        Used to submit information to the server.

@WebServlet("/message/add")
public class AddMessage extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int result = -1;
        // 1.得到前端参数并效验
        String from = req.getParameter("from");
        String to = req.getParameter("to");
        String msg = req.getParameter("msg");
        if (StringUtils.hasLength(from) && StringUtils.hasLength(to)
                && StringUtils.hasLength(msg)) {
            // 2.将表白对象加入到集合
            // 2.1 得到 Connection
            Connection connection = DBUtils.getConnection();
            // 2.2 拼接 sql,创建执行器
            String sql = "insert into messages(`from`,`to`,`message`) values(?,?,?)";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, from);
            statement.setString(2, to);
            statement.setString(3, msg);
            // 2.3 执行执行器,并返回结果
            result = statement.executeUpdate();
            // 2.4 关闭资源
            DBUtils.close(null, statement);
        }
        resp.setContentType("text/html; charset=utf-8");
        resp.getWriter().println(result);
    }
}

3.4 Query information class ( MessageList )

        Used to get all the information on the server.

@WebServlet("/message/list")
public class MessageList extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 查询数据库中的表白列表
        List<Message> list = new ArrayList<>();
        // 1.得到 connection
        Connection connection = DBUtils.getConnection();
        // 2.拼接SQL,创建执行器
        String sql = "select * from messages";
        PreparedStatement statement = connection.prepareStatement(sql);
        // 3.执行SQL,返回 resultSet 并循环将数据添加到 list 中
        ResultSet resultSet = statement.executeQuery();
        while (resultSet.next()) {
            String from = resultSet.getString("from");
            String to = resultSet.getString("to");
            String message = resultSet.getString("message");
            list.add(new Message(from, to, message));
        }
        // 4.关闭资源
        DBUtils.close(resultSet, statement);
        resp.setContentType("application/json; charset=utf-8");
        ObjectMapper objectMapper = new ObjectMapper();
        resp.getWriter().println(objectMapper.writeValueAsString(list));
    }
}

4. Front-end code

<!DOCTYPE html>
<html lang="en">

<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>
    <style>
        body {
            background-image: url(image/wall.jpeg);
            background-repeat: no-repeat;
            background-size: cover;
        }

        * {
            margin: 0;
            padding: 0;
        }

        .container {
            width: 400px;
            margin: 0 auto;
        }

        h1 {
            text-align: center;
            padding: 20px 0;
            color: rgb(11, 213, 248);
        }

        p {
            color: rgb(226, 87, 129);
            text-align: center;
            font-size: 14px;
            padding: 10px 0;
        }

        .row {
            height: 40px;
            width: 350px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .row1 {
            height: 40px;
            display: flex;
            justify-content: center;
            align-items: center;
            padding-left: 20px;
        }

        span {
            width: 70px;
            line-height: 40px;
        }

        .edit {
            color: rgb(41, 227, 134);
            text-align: center;
            width: 261px;
            height: 30px;
            padding-right: 15px;
        }

        .submit {
            width: 280px;
            height: 40px;
            color: white;
            background-color: orange;
            border: none;
        }

        .submit:active {
            background-color: #666;
        }

        .msg {
            width: 100%;
            height: 25px;
            color: rgb(48, 66, 227);
            justify-content: center;
            align-items: center;
            text-align: center;
            padding-top: 10px;
        }
    </style>
    <script src="js/jquery-1.9.1.min.js"></script>
</head>

<body>
    <div class="container">
        <h1>表白墙</h1>
        <p>&nbsp;&nbsp;&nbsp;给他/她留下一句话吧!</p>
        <div class="row">
            <span style="color: rgb(236, 10, 244)">谁: </span>
            <input id="from" class="edit" type="text">
        </div>
        <div class="row">
            <span style="color: rgb(236, 10, 244)">对谁: </span>
            <input id="to" class="edit" type="text">
        </div>
        <div class="row">
            <span style="color: rgb(236, 10, 244)">说: </span>
            <input id="message" class="edit" type="text">
        </div>
        <div class="row1">
            <input type="button" value="表白" class="submit" onclick="mySubmit()">
        </div>
    </div>
    <div id="allMsg"></div>

    <script>
        // 添加表白信息
        function mySubmit() {
            var from = jQuery("#from");
            var to = jQuery("#to");
            var msg = jQuery("#message");
            // 1.非空效验
            if (from.val() == "" || to.val() == "" || msg.val() == "") {
                alert("请输入表白信息!")
                if (from.val() == "") {
                    from.focus();
                }
                if (to.val() == "") {
                    to.focus();
                }
                if (msg.val() == "") {
                    msg.focus();
                }
                return;
            }
            // 2.ajax 提交数据给后端
            jQuery.ajax({
                url: "message/add",   // 提交到后端的地址
                type: "POST", // 提交类型
                data: {
                    from: from.val(),
                    to: to.val(),
                    msg: msg.val()
                }, // 参数
                success: function (result) { // 后端返回给前端的数据
                    if (result != null && result > 0) {
                        alert("表白成功!");
                        from.val('');
                        to.val('');
                        msg.val('');
                        // 刷新表白列表
                        getAllMsg();
                    } else {
                        alert("表白失败!");
                    }
                }
            });
        }

        // 查询所有的表白信息
        function getAllMsg() {
            jQuery.ajax({
                url: "message/list",
                type: "GET",
                data: {},
                success: function (result) {
                    if (result != null && result.length > 0) {
                        // 表示有表白数据
                        var msgHtml = "";
                        for (var i = 0; i < result.length; i++) {
                            msgHtml += '<div class="msg">' +
                                result[i].from + '对' +
                                result[i].to + '说: ' +
                                result[i].message + '</div>';
                        }
                        jQuery("#allMsg").html(msgHtml);
                    } else if (result != null && result.length == 0) {
                        // 没有表白数据
                        console.log("没有表白信息");
                    } else {
                        alert("访问出错!");
                    }
                }
            });
        }
        getAllMsg(); // 执行方法

    </script>
</body>

</html>

5. Create the database

        Create the database and add the messages table.

-- 设置编码格式
set character_set_database=utf8; 
set character_set_server=utf8;

-- 创建数据库
create database if not exists messagewall; 

-- 使用数据库
use messagewall;

-- 创建messages表
drop table if exists messages;
create table messages (`from` varchar(255), `to` varchar(255), `message` 
varchar(2048));

6. Deploy the project

(1) To configure Tomcat in IDEA, you need to download a plugin first:

(2) Then click Add Configuration

 (3) Select Tomcat

 (4) You can change the name, then click ok

 (5) Start Tomcat

 This means that the startup is successful!

(6) Enter the corresponding URL of the project in the browser

 Successful visit!

7. Effect display

Initial interface:

Query the database:

 

Database is empty! 

Enter the information and click Confess:

 Prompt confession success! And the information obtained from the server is shown below:

 Query the information in the database:

 

You can see that the data was successfully written to the database! 

It's over! I wish you all a happy 520!

Guess you like

Origin blog.csdn.net/m0_59140023/article/details/124871328