Servlet (knowledge point + instance project)

Keywords: Java JavaEE Tomcat Back-end

Previous review

1. What is API:

① API is application programming interface;
② It includes source code, bytecode and help documents (note that the version number is consistent).

2.JavaSE and JavaEE:

① JavaSE:
<1> Javase is the standard version of java and has a set of basic class libraries;
<2> The source code is stored in Java_ Under home \ src.zip;
<3> Bytecode stored in JRE_HOME\lib\rt.jar;
②JavaEE:
<1> JavaEE is the enterprise version of java, with a set of enterprise project class libraries;

3.B/S architecture and C/S architecture:

C/S architecture:

<1> C / S architecture is client / server; (APP)
<2> Advantages and disadvantages of C / S architecture:
advantage:
① Fast speed and good user experience;
② Most of the data is inherited to the client, which is relatively safe;
Disadvantages:
① When upgrading, there are many upgraded parts;
② Specific software needs to be installed to access the server.

B/S architecture:

<1> B / S architecture is browser / server; (web page);
<2> Advantages and disadvantages of B / S architecture:
advantage:
① No need to install, just have a browser;
② Upgrade only needs to upgrade the server side;
Disadvantages:
① All data is inherited on the server side, which is relatively unsafe;
② Slow speed and poor user experience;

Servlet

"serv" stands for server side and "let" stands for applet;
The local IP address is 127.0.0.1 or localhost;

1. Preparation

Configure environment variables:

① New JAVA_HOME variable, the value is jdk installation path;
② Add ① to the path;
③ New CATALINA_HOME variable, the value is Tomcat installation path;
④ Add ③ to the path.

Tomcat:

① Tomcat server is a free open source Web application server;
② Opening and closing of Tomcat:
Start: TomcatX/bin/startup.bat(windows),startup.sh(linux);
Close: TomcatX/bin/shutdown.bat(windows),shutdown(linux);

2. Development process

(1) Text file development process:

Erection:

① Create a folder anywhere;
② Front end folders such as html can be established in the folder to store front-end files;
③ Create a WEB-INF folder in the folder (required);
④ The WEB-INF must contain:
<1> Classes folder: used to store bytecode files;
<2> Lib folder: used to store jar packages;
<3> Web.xml file: store "writing specification";

web.xml file writing specification:

<servlet>
	<servlet-name>(Implementation class variable)</servlet-name>
	<servlet-class>(Implementation classpath)</servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name>(Implementation class variable)</servlet-name>
	<url-pattern>(/+alias)</url-pattern>
</servlet-mapping>

Deployment:

Copy the general folder to TomcatX/webapps package;

visit:

<1> The startup operation runs tomcat;
<2> Access localhost:8080 / (folder name + pathname).

(2) Servlet interface:

Servlet interface: (javax.servlet.Servlet)

① The lib file under the Tomcat server has a jar package to store the Servlet interface;
② The Http server can only call [dynamic resource file], that is, the implementation class of Servlet;

HttpServlet abstract class:

① HttpServlet is an abstract class and a subclass of Servlet;
② Comparison with Servlet:
<1> Servlet is an interface that calls five abstract methods that need to be implemented internally;
<2> Httpservlet is an abstract class. To call it, you only need to override the internal service() method;
<3> Compared with Servlet, httpservlet has the following advantages: reducing the difficulty of implementing classes in the interface;
It is also an advantage of abstract classes over interfaces.

(3) Lifecycle of Servlet object:

summary:

① Its implementation class instance object can only be created by Http server;
② By default, the Http server creates an instance object when it receives the first request from the Servlet;
③ When Http is running, a Servlet can only create one instance object (process), and the access of different users is multithreaded;
④ When Http is closed, all Servlet objects are automatically destroyed.

When modifying and creating an instance object, start the execution for the web page:

<servlet>
	...
	<load-on-startup>(Integer greater than 0)</load-on-startup>
</servlet>

(4) HttpServletResponse interface:

HttpServletResponse overview:

① The interface comes from the Servlet interface;
② The interface implementation class is provided by the Http server;
③ Write doGet or doPost methods into the response body and give them to the browser.

HttpServletResponse function:

① Write the corresponding results to the response body in binary:
Comparison between print and write:
<1> The write () method will convert the incoming int type data into ASCII corresponding characters;
<2> The print () method will normally output the incoming int type data.

protected void doGet(HttpServletResponse response,HttpServletRequest){
	//results of enforcement
	String result = "...";	
	//Get the output stream
	PrintWriter pw = response.getWriter();	
	//Print the execution result to the browser with write(...)
	pw.write(result);
	
	//Print the execution result to the browser with print(...)
	pw.print(result);			
}

② Modify the compilation mode of output to the browser:
Before getting the output stream:

//You can print html statements on the browser
response.setContentType("text/html");

//You can print Chinese on the browser
response.setContentType("text;charset=utf-8");

③ Control the browser to send a request to the specified server:

response.sendRedirect("(URL path)");

(5) HttpServletRequest interface:

HttpServletRequest overview:

① From Servlet interface;
② The implementation class of the interface is provided by Http;
③ This interface is responsible for reading the information in the Http protocol package when the doGet() or doPost() method is running.

HttpServletRequest function:

① Read the [request line] information in the Http protocol package;

//Read URL information
String url = request.getRequestURL().toString();
//Read method information
String method = request.getMethod();
//Read URI information (string interception of URL)
String uri = request.getRequestURI();

② Read the request object to obtain the request parameters and names in the [request header];

//Get all parameter names (return enumeration class)
Enumeration paramNames = request.getParameterNames();
//Traversing enumeration classes (similar to iterators traversing collections)
while(paramNames.hasMoreElements()){
	String paramName = (String)paramNames.nextElement();
	//Get request parameter value
	String value = request.getParameter(paramName);
}

③ Obtain parameter information from [request body] (doPost() method)

//Get parameter value
String value = request.getParameter(paramName);

④ The decoding method of the modification request body is utf-8:

request.setCharacterEncoding("utf-8");

Response and Request lifecycles:

① When the Http server receives the "request protocol package" sent by the browser, it will automatically generate a [request object] and a [response object];
② When Http calls the do... () method. Be responsible for passing the request object and response object into the method as arguments;
③ After the do... () method, the Tomcat server is responsible for destroying them.

(6) Detailed explanation of Internet communication (B/S architecture):

B/S architecture diagram

Internet communication diagram

(7) Project practice -- examination information management system

<1> 1. Project structure:

Task:
Online examination management system -- user information management module
Branch task:
>User information registration
>User information query
>User information deletion
>User information update
File schema:

preparation:
1. Create user information table t_users.frm

 drop table if exists t_users;
    create table t_users(
        userId int primary key auto_increment,       #User number (auto increment operation)
        userName varchar(255),        #User name
        password varchar(255),        #User password
        sex      varchar(10),             #User gender
        email    varchar(255)         #User mailbox
    )

2. Insert user information

insert into t_users(userName,password,sex,email)
    values('shawn','666','man','shawn@126.com');
    ...

3. Create a new entity class users (under the entity package).

public class Users {
    //Properties of the user entity class
    private Integer userId;
    private String userName;
    private String password;
    private String sex;
    private String email;

    //Construction method (no parameters)
    public Users(){}

    //Construction method (with reference)
    public Users(Integer userId,String userName,String password,String sex,String email){
        this.userId = userId;
        this.userName = userName;
        this.password = password;
        this.sex = sex;
        this.email = email;
    }

    //set method and get method
    public void setUserId(Integer userId){
        this.userId = userId;
    }

    public Integer getUserId(){
        return userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

4. Under the WEB-INF directory, create a lib folder to store the JDBC implementation jar package provided by mysql.

<2> Project process:

a. Front end web page code (user_Add.html):
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>UserTestInformationManage_System</title>
</head>
<body>
    <center>
        <form action="/myWeb/user/add" method="get">
            <table border="2">
                <tr>
                    <td>User name</td>
                    <td><input type="text" name="userName"/></td>
                </tr>
                <tr>
                    <td>User password</td>
                    <td><input type="password" name="password"/> </td>
                </tr>
                <tr>
                    <td>User gender</td>
                    <td>
                        <input type="radio" name="sex" value="male"/>male
                        <input type="radio" name="sex" value="female"/>female
                    </td>
                </tr>
                <tr>
                    <td>User mailbox</td>
                    <td><input type="text" name="email"/> </td>
                </tr>
                <tr>
                    <td><input type="submit" value="User registration"/> </td>
                    <td><input type="reset" name="Reset"/> </td>
                </tr>
            </table>
        </form>
    </center>
</body>
</html>

effect:

b. Write JDBC code for inserting data in UserDao class (under dao package):
package com.shawnWeb.dao;

import com.shawnWeb.entity.Users;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class UserDao2 {
    public UserDao2(){}

    public int add(Users users){
        Connection conn = null;
        PreparedStatement ps = null;
        int result = 0;

        String url = "jdbc:mysql://localhost:3306/bjpowernode";
        String user = "root";
        String password = "123456";

        //Register driver
        try {
            Class.forName("com.mysql.jdbc.Driver");
            //Get database connection
            conn = DriverManager.getConnection(url,user,password);
            //Get database operation object
            String sql = "insert into t_users(userName,password,sex,email)"+
                    " values(?,?,?,?)";
            ps = conn.prepareStatement(sql);
            //Here? Value transmission
            ps.setString(1,users.getUserName());
            ps.setString(2,users.getPassword());
            ps.setString(3,users.getSex());
            ps.setString(4,users.getEmail());

            //Execute sql statement
            result = ps.executeUpdate();

            //
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if (ps != null){
                try {
                    ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (conn != null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            return result;
        }
    }
}
c. Write doGet(...) method (simulate Internet communication process):
package com.shawnWeb.controller;

import com.shawnWeb.dao.UserDao2;
import com.shawnWeb.entity.Users;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class UserAddServlet2 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName,password,sex,email;
        //Create a User object to store User information transmitted from the browser
        Users user = null;
        //Create a Dao object to call the registration method described below
        UserDao2 dao2 = new UserDao2();
        //Return value of insert data
        int result = 0;
        //Create an output stream to print the results to the browser
        PrintWriter out = null;

        //1. Call the request object to read the request header parameter information and get the user's information
        userName = request.getParameter("userName");
        password = request.getParameter("password");
        sex = request.getParameter("sex");
        email = request.getParameter("email");

        //2. Use JDBC to fill user information into MySQL database
        //Store user information in user
        user = new Users(null,userName,password,sex,email);
        result = dao2.add(user);
        //3. Call the response object to pass the processing result into the response body in binary form
        //Change the encoding mode of the browser so that it can compile its html and Chinese
        response.setContentType("text/html;charset=utf-8");
        //Get the output stream of the responder
        out = response.getWriter();
        if (result == 1){
            out.print("<font style='color:red;font-size:40'>User information registration succeeded</font>");
        }else{
            out.print("<font style='color:red;fond-size:40'>User information registration failed</font>");
        }

    }
    //After doGet, Tomcat is responsible for destroying the request object and the response object
    //tomcat is responsible for pushing the HTTP protocol package to the requesting browser
    //The browser specifies the compiler to edit the binary content of the response body according to the response header content type
    //The browser displays the edited results to the user in the window [end of Internet communication]
}
Result display:

I. enter the registration data in the input box:

II. Click the user registration button to pop up registration success:

III. open t in the database_ Users table, verifying data insertion:

Ⅳ. The data is inserted successfully, and the insertion function is completed!

Posted by Dale_G on Mon, 20 Sep 2021 11:38:53 -0700