520 está aquí, te enseña a hacer un pequeño proyecto de muro de confesión de JavaWeb

contenido

1. Configurar el proyecto Maven

1.1 Crear un proyecto Maven

1.2 Introducción de dependencias relacionadas

1.3 Estructura general del proyecto

2. Interfaz de interacción front-end y back-end acordada

3. Código del servidor

3.1 Crear la clase Mensaje

3.2 Crear clase de herramienta

3.3 Agregar clase de mensaje (AddMessage)

3.4 Clase de información de consulta (MessageList)

4. Código de front-end

5. Crea la base de datos

6. Implementar el proyecto

7. Visualización de efectos


1. Configurar el proyecto Maven

1.1 Crear un proyecto Maven

Después de eso, seleccione la ruta de almacenamiento y el nombre, que es relativamente simple, ¡así que no entraré en detalles!

1.2 Introducción de dependencias relacionadas

Introduzca las dependencias de servletjackson , mysql-connector y lombok en 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 Estructura general del proyecto

 

2. Interfaz de interacción front-end y back-end acordada

        La llamada "interfaz de interacción front-end y back-end" es un enlace clave en el desarrollo web, específicamente: qué solicitudes HTTP pueden enviar la página al servidor y qué respuestas HTTP se esperan obtener para cada solicitud.

  1. Obtenga toda la información del servidor
    Solicitud: GET
    Respuesta: formato JSON
  2. Enviar información al servidor
    Solicitud: formato JSON
    Respuesta: formato JSON

3. Código del servidor

3.1 Crear la clase Mensaje

@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;
    }
}

Nota: @Setter y @Getter generarán automáticamente todos los métodos get y set.

3.2 Crear clase de herramienta

Cree la clase DBUtils para conectarse a la base de datos.

La clase DBUtil implementa principalmente las siguientes funciones:

  • Cree una instancia de MysqlDataSource y establezca propiedades como URL, nombre de usuario, contraseña, etc.
  • Proporcione el método getConnection para establecer una conexión con el servidor MySQL.
  • Proporciona un método cercano para liberar los recursos necesarios.
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();
        }
    }
}

Cree la  clase StringUtils para la nulabilidad:

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

3.3 Agregar clase de mensaje ( AddMessage )

        Se utiliza para enviar información al servidor.

@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 Clase de información de consulta ( MessageList )

        Se utiliza para obtener toda la información en el servidor.

@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. Código de front-end

<!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. Crea la base de datos

        Cree la base de datos y agregue la tabla de mensajes.

-- 设置编码格式
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. Implementar el proyecto

(1) Para configurar Tomcat en IDEA, primero debe descargar un complemento:

(2) Luego haga clic en Agregar configuración

 (3) Seleccione Tomcat

 (4) Puede cambiar el nombre, luego haga clic en Aceptar

 (5) Iniciar Tomcat

 ¡Esto significa que la puesta en marcha es exitosa!

(6) Introduzca la URL correspondiente del proyecto en el navegador

 ¡Visita exitosa!

7. Visualización de efectos

Interfaz inicial:

Consulta la base de datos:

 

¡La base de datos está vacía! 

Ingrese la información y haga clic en Confesar:

 ¡Éxito de la pronta confesión! Y la información obtenida del servidor se muestra a continuación:

 Consultar la información en la base de datos:

 

¡Puede ver que los datos se escribieron correctamente en la base de datos! 

¡Se acabó! ¡Les deseo a todos un feliz 520!

Supongo que te gusta

Origin blog.csdn.net/m0_59140023/article/details/124871328
Recomendado
Clasificación