Servlet realizes simple front-end and back-end interaction

Servlet realizes simple front-end and back-end interaction

First, what is the front-end and back-end interaction?

In my understanding, it is probably like this:

In short, it is data exchange

Next, let's see how to implement this simple interaction:

1. First, we don't write a static page at the front end, but directly put the requested parameters on the url
2. The first thing the backend needs to do is to connect to the database. If the database is not connected, then two Han and Han are giggling
3. Accept the parameters requested by the front end and query the requested parameters in the database
4. The back end returns the result to the front end, and an interaction is completed

Database:


The database statement is as follows:

Table creation:
DROP TABLE IF EXISTS `stus`;
CREATE TABLE `stus`  (
  `id` int(0) NOT NULL AUTO_INCREMENT,
  `loginName` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  `loginPwd` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;


Insert data:
INSERT INTO `stus` VALUES (1, '123', '123');
INSERT INTO `stus` VALUES (2, 'Xiao Ming', '111');
INSERT INTO `stus` VALUES (3, 'xs', '111');

url request from the front end:

Note that & & is used to connect multiple parameters
Here, 8080 is my port number, and name=123 and passwd=123 are the request parameters defined by the front and rear ends. After all, the front and rear ends don't have a sense of communication. Tell the back end that the front end needs to query whether the user name and password exist.

Servlet realizes front-end and back-end interaction, and Tomat needs to be configured in the idea
Now I suddenly understand why I can't run if I read other programs without reporting errors. Servlet doesn't write the main function. The main function is in Tomcat. Tomcat is not configured in idea. Everything is seasonal!


If you want to configure your friend, please see this article
[https://blog.csdn.net/weixin_50569789/article/details/119817928]

Everything is ready. Now start writing the backend:

Connect to database

JDBC is used to connect to the database, and the jar package needs to be imported
Enter the official website download address:
https://dev.mysql.com/downloads/connector/j/

 static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

Note that I use the MySQL 8 version of the database, so it's com mysql. cj. jdbc. Driver, if you are version 5, it is com mysql. jdbc. Driver.
We write class The purpose of forname ("com.mysql.cj.jdbc.Driver") is to load the database driver, so why write this sentence?

My personal understanding is that we connect to the database through jdbc. For example, if we want to use a method of a class, we need to instantiate a new object to call methods or properties. However, jdbc is only an empty interface or a new one. At this time, you need to use specific methods to load and instantiate it.

    private static final String url = "jdbc:mysql://localhost:3306/vote?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
    private static final String userName = "root";
    private static final String passwd = "root";
	Connection conn = DriverManager.getConnection(url, userName, passwd);

Here are the database connection objects, such as which database you want to connect to, the password and user name of the database, etc

useSSL: in the higher version of MySQL, you need to specify whether to connect with SSL (useSSL is used to ensure the security of Internet data transmission and use data encryption)

serverTimezone: This is the time zone. UTC represents a globally unified time. For specific projects, the time should be set according to their own time zone, such as serverTimezone=Asia/Shanghai in China. Other parameters you are interested in viewing by yourself.

How does the back end get the request from the front end?

In the Servlet, the request of the get method is the front-end request. The request is a whole. You need to get the parameters you want through specific methods and parameters.

 String pa = req.getParameter("name");
 String pa1 = req.getParameter("passwd");

Get the front-end parameters and put them into the database for query

PreparedStatement ps = conn.prepareStatement("select * from stus where loginName =? and loginPwd =?;")
ps.setString(1, pa);
ps.setString(2, pa1);

It is recommended that you use prepareStatement here. The advantage is that it can prevent sql injection. Of course, it is precompiled, which can improve the efficiency of batch processing.

Returns the parameters of the front-end request

PreparedStatement ps = conn.prepareStatement("select * from stus where loginName =? and loginPwd =?;")
ResultSet rs = ps.executeQuery();
while (rs.next()) {
      resp.getWriter().println("id:" + rs.getInt("id"));
      resp.getWriter().println("loginName:" + rs.getString("loginName"));
      resp.getWriter().println("loginPwd:" + rs.getString("loginPwd"));
            }

As you can see here, PreparedStatement precompiled calls the executeQuery() method through the SQL statement written by itself to return the result set of a query.


In addition, the resp here is the corresponding request reply. To return the query result to the front end, we need to use the getWriter() method of resq

Finally, go and see if you have the front-end data

Finally, a common problem is summarized:


See Java During lang. String, I guess there should be a conflict. At this time, you can put the mouse over the String and press ctrl to see if it refers to what you want

For example, I have a class built by String, which was used to test the results and forgot to delete it. One thing you can pay attention to here is that the class name should not use special characters as much as possible, which can easily lead to conflicts and program errors

Finally, paste the source code, and interested friends can try it

package com.example.demo.day1204;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @Author:Yun
 * @Date:2021/12/23/15:20
 * @Description:
 **/
@WebServlet(name = "testHelloWorld", urlPatterns = "/hello")
public class HelloWord extends HttpServlet {
        private static final java.lang.String url = "jdbc:mysql://localhost:3306/vote?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
        private static final java.lang.String userName = "root";
        private static final java.lang.String passwd = "root";

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)  {
        resp.setHeader("Content-Type", "application/json;charset=UTF-8");
        String pa = req.getParameter("name");
        String pa1 = req.getParameter("passwd");
        try (
                Connection conn = DriverManager.getConnection(url, userName, passwd);
             PreparedStatement ps = conn.prepareStatement("select * from stus where loginName =? and loginPwd =?;"))
        {
            ps.setString(1, pa);
            ps.setString(2, pa1);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                resp.getWriter().println("id:" + rs.getInt("id"));
                resp.getWriter().println("loginName:" + rs.getString("loginName"));
                resp.getWriter().println("loginPwd:" + rs.getString("loginPwd"));
            }
            rs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

If you have any questions, please leave a message for discussion.

Keywords: Front-end

Added by ecxzqute on Tue, 04 Jan 2022 05:39:34 +0200