Servlet

About System Architecture

  1. What forms does the system architecture include?
    • C/S architecture
    • B/S architecture
  2. C/S architecture?
    • Client/Server
    • What are the C/S architecture software or systems?
      • QQ (first go to Tencent official website to download a QQ software, dozens of MB, and then put the client software installed, and then enter the QQ number and password, after logging in, you can chat with your friends, you can use this software.)
    • C/S architecture features: Specific client software needs to be installed.
    • What are the system advantages and disadvantages of C/S architecture?
      • Advantages:
        • High speed (most of the data in the software is integrated into the client software, and a small amount of data is transmitted from the server, so the C/S structure of the system is fast)
        • Good experience (fast and cool interface, of course good experience.)
        • Interface cool (special language to achieve the interface, more flexible.)
        • Low server pressure (because a lot of data is integrated in the client software, so the server only need to transfer a small amount of data, of course the server pressure is low).
        • Security (because a large amount of data is integrated in the middle of the client software, and the client has a lot of, the server though there is only one, even if the server side of the earthquake, fire, the server was damaged, the problem is not big, because a large amount of data cache on multiple clients, have store, so from this aspect, C/S structure of the system is safe.)
        • .
      • Disadvantages:
        • Upgrade maintenance is poor. (Upgrade and maintenance is troublesome. The cost is relatively high. Every client software needs to be upgraded. Some software is not so easy to install.
  3. B/S architecture?
    • B/S (Browser/Server, Browser/Server)
    • www.baidu.com
    • www.jd.com
    • www.126.com
    • Is the B/S structured system a special C/S system?
      • In fact, the B/S structure of the system is still a C/S, but this C is special, the Client is a fixed browser software.
    • The advantages and disadvantages of B/S system are as follows:
      • Advantages:
        • Easy to upgrade and maintain, low cost. (Just update the server side.)
        • No need to install specific client software, user operation is extremely convenient. Just open your browser and type in the url.
      • Disadvantages:
        • Slow speed (not because of low bandwidth, because all the data is on the server, every request sent by the user is required to fully respond to the server data, so the B/S structure system transmits a large amount of data in the network.)
        • Poor experience (the interface is not that cool because the browser only supports three languages: HTML, CSS, and JavaScript. Plus slow speed.)
        • Unsafe (All data are stored on the server. If fire or earthquake occurs on the server, all data will be lost.)
        • .
  4. C/S or B/S structured systems, which is better or worse?
    • This is a poor question. It’s not that one is better than the other. Different systems have different application scenarios in different service scenarios.
    • Recommended use of entertainment software?
      • C/S structure
    • What business software do you recommend for internal use?
      • A system used internally that requires low maintenance costs.
      • It doesn’t have to be cool to use in the company.
      • The enterprise system used by the company is mainly capable of data maintenance.
      • B/S structure.
  5. Note: the development of B/S structure of the system, in fact, is the development of a WEB site, in fact, the development of a WEB system.
    • What skills do you need to develop a WEB system?
      • WEB front-end (a program that runs on a browser.
        • HTML
        • CSS
        • JavaScript
      • WEB back end (WEB server side program.)
        • Java can (Java does WEB development we call JavaWEB development. Java Web development core specification: Servlet [Server Applet server-side Java applets. )
        • C also works
        • C + + can also be
        • Python also line
        • PHP can also
        • .
  6. What is JavaEE?
    • Java consists of three major pieces:
      • JavaSE
        • Java Standard edition (a set of class library: someone else wrote a set of class library, but this class library is the standard class library, go EE, or go ME, this SE must be the foundation, learn first.)
      • JavaEE (WEB direction, WEB systems.)
        • Java Enterprise Edition (also a set of class libraries: is also a set of class libraries written by others, but this class library can help us complete the development of enterprise projects, specifically for enterprise internal solutions to provide a set of libraries (multiple sets).
        • Someone else wrote it, you use it, you can develop enterprise projects with it.
        • Web systems can be developed.
        • Java is popular in this JavaEE direction.
      • JavaME
        • Java Micro Edition (again a set of class libraries, but this set of class libraries to help us with the development of electronic micro device kernel programs)
        • Set top box kernel program, vacuum cleaner kernel program, refrigerator kernel program, rice cooker kernel program…
    • JavaEE actually includes many specifications, 13 of which Servlet is one of the JavaEE specifications. Learn Servlet or Java language.

B/S structure system communication principle (not involving Java applets)

  • WEB system access process
    • Step 1: Open your browser
    • Step 2: Find the address bar
    • Step 3: Enter a legitimate web address
    • Step 4: Enter
    • Step 5: The result of the response is displayed in the browser.
  • About Domain name:
    • www.baidu.com/ (website)
    • www.baidu.com is a domain name
    • Enter the domain name in the address bar of the browser and press Enter. The domain name resolver displays the IP address and port number of the domain name.
    • Analytical results may be: http://110.242.68.3:80/index.html
  • What’s the IP address?
    • An identification number for a computer in a network. IP addresses are unique on the same network.
    • In order for Computer A to communicate with computer B, you first need to know the IP address of computer B to establish A connection.
  • What is the port number?
    • One port represents a piece of software (one port represents an application, one port represents only a service).
    • There are many programs in a computer, and each program has a port number after it is started.
    • Port numbers are unique on the same computer.
  • How does a WEB system communicate? Communication steps:
    • Step 1: The user enters the URL
    • Step 2: domain DNS resolver: http://110.242.68.3:80/index.html
    • Step 3: the browser software searches the network for 110.242.68.3 until it finds the host.
    • Step 4: Locate the server software on 110.242.68.3. Because it is port 80, you can easily locate the server software corresponding to port 80.
    • Step 5: The server software corresponding to port 80 knows that the browser wants the resource name: index.html
    • Step 6: The server software finds the index.html file and outputs the contents of the index.html file directly to the browser.
    • Step 7: The browser receives the code from the server (HTML CSS JS)
    • Step 8: browser render, execute HTML CSS JS code, show the effect.
  • What is a URL?
    • Uniform Resource Locator (www.baidu.com)
  • What is a request and what is a response?
    • What the request and response really say is that the data flows in different directions.
    • Sending data from the Browser side to the Server side is called a request. English word: request
    • Sending data from the Server side to the Browser side is called a response. English word: Response
    • B –> S (request request)
    • S –> B

About WEB server software

  • What does WEB server software have? (The software was developed in advance.)

    • Tomcat (WEB Server)
    • Jetty (WEB Server)
    • JBOSS (Application Server)
    • WebLogic (Application Server)
    • WebSphere (Application Server)
  • The relationship between application server and WEB server?

    • The application server implements all the JavaEE specifications. (JavaEE has 13 different specifications.)
    • WEB server only implemented Servlet + JSP in JavaEE two core specifications.
    • The application server includes a WEB server.
    • For those of you who have used the JBOSS server, it should be clear that there is a Tomcat server embedded in JBOSS.
  • Tomcat download

    • The apache official website is www.apache.org/
    • Tomcat official website: tomcat.apache.org
    • Tomcat is an open source and free lightweight WEB server.
    • Tomcat also has another name: Catalina. Tomcat is also known as Catalina because it is small and fast, and it is said that the author developed a lightweight WEB server on a beautiful island in the US.
    • Tomcat’s logo is a male cat (meaning that tomcat server is light and compact, sure enough, small size, fast running, only implemented the Servlet+JSP specification)
    • Tomcat is written in the Java language.
    • In order for the Tomcat server to run, the JRE (Java runtime environment) must be installed.
  • To run the Tomcat server, you need to install the Java Development Kit (JDK) and configure the Java runtime environment.

    • JAVA_HOME = C: \ Program Files \ Java \ JDK – 17.0.1
    • PATH=%JAVA_HOME%\bin
    • JAVA_HOME is not currently configured. Right now, it’s ok to just run Java programs. Are you sure?
  • Installation of Tomcat server:

    • The green version is easy to install, directly decompress the ZIP package. Decompression is installation.
    • I have a good habit of creating a dev directory in the root directory of drive C. All Java development tools are installed in the dev directory, which is easier to manage. (Be my guest)
    • Start Tomcat
      • The file startup.bat in the bin directory is used to start the Tomcat server.
        • What is the xxx.bat file? Bat file is dedicated to Windows operating system, bat file is a batch file, this file can write a large number of Windows DOS commands, and then execute bat file is equivalent to execute DOS commands in batch.
        • Startup. sh: this file cannot be executed on Windows, but can be used on Linux. In The Linux environment, you can execute shell commands. A large number of shell commands are written in shell files, and then you can execute shell commands in batches by executing this shell file.
        • The Tomcat server provides bat and SH files to illustrate the versatility of the Tomcat server.
        • Bat file: catalina.bat file: catalina.bat file: catalina.bat
        • Catalina. Bat file have such a line in the configuration: MAINCLASS = org. Apache. Catalina. Startup. The Bootstrap (this class is the main method of class).
        • The Tomcat server is written in Java, and since it is written in Java, starting the Tomcat server is to execute the main method.
      • We tried to start the Tomcat server by entering startup.bat in the DOS command window.
      • You cannot configure only the bin directory corresponding to the path to start the Tomcat server. There are two environment variables that need to be configured:
        • JAVA_HOME = JDK root
        • CATALINA_HOME= Root of the Tomcat server
  • Directories about the Tomcat server

    • Bin: This directory stores the command files of the Tomcat server, such as starting or stopping Tomcat.
    • Conf: This directory is the directory where the Tomcat server configuration files are stored. (Port number can be configured in server.xml file, default Tomcat port is 8080)
    • Lib: This directory is the core program directory of the Tomcat server, because the Tomcat server is written in Java. The jar packages in this directory contain class files.
    • Logs: Log directory of the Tomcat server. Log files are generated in this directory for information about Tomcat server startup.
    • Temp: indicates the temporary directory of the Tomcat server. Store temporary files.
    • Webapps: this directory is used to store a large number of WebApps.
    • Work: This directory is used to store Java files translated from JSP files and compiled from class files.
  • What environment variables are required to configure the Tomcat server?

    • JAVA_HOME = JDK root
    • CATALINA_HOME= Root of the Tomcat server
    • PATH=%JAVA_HOME%\bin; %CATALINA_HOME%\bin
  • Start Tomcat: startup

  • Shutdown Tomcat: stop (shutdown.bat file renamed to stop.bat. Why? The shutdown command conflicts with the Shutdown command in Windows. So change it.)

  • How to test whether the Tomcat server is started successfully?

    • Open your browser and enter the URL in the browser’s address bar:
      • http://ip Address: port number
      • What is the IP address? I know the port number. It’s 8080
      • The local IP address is either 127.0.0.1 or localhost.

Implement a basic Web application (without Java applets)

  • Step 1: find CATALINA_HOME\webapps directory

    • Because all webapps need to be in the Webapps directory. (There is no reason, this is a requirement of the Tomcat server. The Tomcat server will not find your application unless you put it here.
  • Step 2: Create a subdirectory in CATALINA_HOME\webapps and name it oa

    • The directory name oa is the name of your webapp.
  • Step 3: Create a resource file in the OA directory, for example, index.html

    • Write the contents of the index.html file.
  • Step 4: Start the Tomcat server

  • Step 5: Open your browser and type this URL in your browser’s address bar:

  • http://127.0.0.1:8080/oa/index.html

  • Consider a question:

    • We type a URL directly into the browser and press Enter. Is this the same as hyperlinking? Since it’s the same, we can definitely use hyperlinks.

      <! Note that the following path, starting with /, with the project name, is an absolute path. No need to add: http://127.0.0.1:8080-->
      <a href="/oa/login.html">user login2</a>
      
      <! -- It doesn't matter if you have multiple levels. -->
      <! Note: our current paths on the front end all start with a "/", with the project name added. -->
      <a href="/oa/test/debug/d.html">d page</a>
      Copy the code
  • http://127.0.0.1:8080/oa/userList.html

    • Visit this address to display a list of users page. But the user list page is written in an HTML file. This resource is called a static resource. How can it be a dynamic resource. You obviously need to connect to the database.
    • The connection database needs JDBC procedures, that is to say, the need to write Java procedures to connect to the database, the number of records in the database, the number of records displayed on the page, this technology is called dynamic web technology. Dynamic web technology does not mean that pages have flash animations. Dynamic web technology means that the data in the page is dynamic and changes according to the data in the database.

For a dynamic Web application, how many roles are involved in a request and response process, and how many protocols exist between roles

  • What are the roles (who are involved in the entire BS structure)

    • Browser software development team (browser software too many: Google Chrome, Firefox, Internet Explorer….)
    • WEB Server development team (WEB Server is also too many software: Tomcat, Jetty, WebLogic, JBOSS, WebSphere….)
    • DB Server development team (DB Server software is also too many: Oracle, MySQL…..)
    • Webapp development team (WEB applications are developed by us as JavaWEB programmers)
  • What specifications and protocols must be followed by roles and between roles

    • There is a set of specifications between the webapp development team and the WEB Server development team: the Servlet specification, one of the JavaEE specifications.
      • What does the Servlet specification do?
        • WEB Server and WebApp are decoupled.
    • There is a transport protocol between Browser and WebServer: HTTP. (Hypertext Transfer Protocol.)
    • There is one specification between the WebApp development team and the DB Server development team: the JDBC specification.
  • What is the Servlet specification?

    • Following the Servlet specification of a WebApp, the WebApp can be run on different WEB servers. (Because the WebApp is Servlet compliant.)
    • What does the Servlet specification include?
      • Which interfaces are regulated
      • Which classes are regulated
      • Defines what configuration files should be in a Web application
      • Specifies the name of a configuration file in a Web application
      • Specifies the path for storing configuration files in a Web application
      • Defines the contents of a configuration file in a Web application
      • Defines what the directory structure of a valid web application should look like.
      • .

Develop a WebApp with servlets (Java applets) (emphasis)

  • What are the development steps?

    • Step 1: Create a new directory under the Webapps directory and name it CRM (which is the name of the WebApp). Of course, it can also be other projects, such as the bank project, which can create a directory bank, and the office system can create an OA.

      • Note: CRM is the root of this WebApp
    • Step 2: Create a new directory under the root of webApp: WEB-INF

      • Note: The name of this directory is specified in the Servlet specification and must be all uppercase and identical. Absolutely absolutely.
    • Step 3: Create a new directory in the WEB-INF directory: classes

      • Note: The name of this directory must be all lowercase classes. This is also specified in the Servlet specification. In addition, this directory must store Java program compiled class files (in this case, bytecode files).
    • Step 4: Create a new directory in the WEB-INF directory: lib

      • Note: This table of contents is not required. However, if a Webapp needs a third-party JAR package, the jar package should be placed in the lib directory, and the name of the directory should not be arbitrary, it must be all lowercase lib. For example, the Java language requires a database driver JAR package to connect to a database. The jar package must be placed in the lib directory. The Servlet specification.
    • Step 5: Create a new file in the WEB-INF directory: web.xml

      • Note: This file is required, and the filename must be called web.xml. This file has to go here. A valid WebApp, web.xml file is required. The web.xml file is a configuration file that describes the contrast between the request path and the Servlet class.

      • This file should be copied from another webapp, preferably not handwritten. There is no need. Copy and paste

      • 
                    
        
        <web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
          version="5.0"
          metadata-complete="true">
        
        
        </web-app>
        
        Copy the code
    • Step 6: Write a Java program, this small Java program can not be developed at will, this small Java program must implement the Servlet interface.

      • The Servlet interface is not in the JDK. (Because servlets are not JavaSE anymore. Servlets belong to JavaEE, which is another set of class libraries.
      • The Servlet interface (servlet.class file) is provided by Oracle. (The original was provided by Sun.)
      • The Servlet interface is a member of the JavaEE specification.
      • The Tomcat server implements the Servlet specification, so the Tomcat server also needs to use the Servlet interface. The Tomcat server should have this interface. The Tomcat server has a servlet-api.jar in the CATALINA_HOME\lib directory. When you unzip the servlet-api.jar, you will see a servlet.class file.
      • Important: Starting with JakartaEE9, the full name of the Servlet interface has changed: jakartaee.servle.servlet
      • Note: When writing this Java applet, you can have the Java source code wherever you like, just place the compiled Class files in the Classes directory.
    • Step 7: Compile the HelloServlet we wrote

      • Important: How can you get your HelloServlet to compile? Configure the environment variable CLASSPATH

        CLASSPATH=.; C: / dev/apache tomcat – 10.0.12 \ lib \ servlet – API jar

      • Question to consider: Does the CLASSPATH configuration above have anything to do with Tomcat server running?

        • It doesn’t matter, this environment variable is only configured so that your HelloServlet will compile correctly to the class file.
    • Step 8: Copy the above compiled helloservlet. class file to web-INF \classes.

    • Step 9: Write configuration information in the web.xml file to associate the “request path” with the “Servlet class name”.

      • This step is described in technical terms: Register the Servlet class in the web.xml file.

      • 
                    
        
        <web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
          version="5.0"
          metadata-complete="true">
        
        	<! -- Servlet description -->
        	<! -- Any servlet corresponds to a servlet-mapping -->
        	<servlet>
        		<servlet-name>fdsafdsagfdsafdsa</servlet-name>
        		<! -- This position must be fully qualified class name with package name -->
        		<servlet-class>com.bjpowernode.servlet.HelloServlet</servlet-class>
        	</servlet>
        
        	<! -- Servlet mapping information -->
        	<servlet-mapping>
        		<! -- This one is also arbitrary, but the content should be the same as above. -->
        		<servlet-name>fdsafdsagfdsafdsa</servlet-name>
        		<! -- You need a path -->
        		<! -- The only requirement for this path is that it must start with a / -->
        		<! -- The current path can be written arbitrarily -->
        		<url-pattern>/fdsa/fd/saf/d/sa/fd/sa/fd</url-pattern>
        	</servlet-mapping>
        	
        </web-app>
        
        Copy the code
    • Step 10: Start the Tomcat server

    • Step 11: Open your browser and enter a URL in the browser address bar. The URL must be:

      • http://127.0.0.1:8080/crm/fdsa/fd/saf/d/sa/fd/sa/fd
      • One very important thing: the request path on the browser cannot be written arbitrarily. The request path must match the URL-pattern in the web.xml file.
      • Note: The only difference between the request path on the browser and the URL-pattern in the web.xml file is that the request path on the browser has the project name: / CRM
    • The path written on the browser is too complex; use hyperlinks instead. (Very important: HTML pages can only be placed outside the WEB-INF directory.)

    • We don’t need to write the main method anymore. The Tomcat server is responsible for calling the main method, which is executed when the Tomcat server starts. We javaweb programmers simply write the implementation class for the Servlet interface and register it in the web.xml file.

    • To summarize: What would a legitimate WebApp directory structure look like?

      Webapproot | -- -- -- -- -- - WEB - INF | -- -- -- -- -- - classes (for bytecode) | -- -- -- -- -- - lib (third party jar package) | -- -- -- -- -- - WEB. XML (the registration Servlet) | -- - | - HTML -- -- -- -- -- - the CSS |------javascript |------image ....Copy the code
    • What happens when the browser sends a request and the final server invokes a method in the Servlet? (The following process is sketchy. There are many other steps I omitted.)

      • User input the URL, or directly click on the link: http://127.0.0.1:8080/crm/fdsa/fd/saf/d/sa/fd/sa/fd
      • Then the Tomcat server receives the request, the clipping path: / CRM/fdsa/fd/saf/d/sa/fd/sa/fd
      • Tomcat server finds the CRM project
      • The Tomcat server in the web. XML file find/fdsa/fd/saf/d/sa/fd/sa/fd corresponds to the Servlet is: com. Bjpowernode.. Servlet HelloServlet
      • Tomcat server by reflection mechanism, create com. Bjpowernode.. Servlet HelloServlet object.
      • Tomcat server call com. Bjpowernode.. Servlet HelloServlet object service method.

About the JavaEE version

  • The latest version of JavaEE is JavaEE8
  • JavaEE was donated by Oracle, which donated the JavaEE specification to Apache.
  • Apache has renamed JavaEE to Jakarta EE instead of JavaEE.
  • There will be no JavaEE. It will be called Jakarta EE.
  • JavaEE8 version of the updated “JavaEE9”, not “JavaEE9” name, called JakartaEE9
  • In JavaEE8, the corresponding Servlet class name is javax.servlet.servlet
  • JakartaEE9 the corresponding Servlet class name is jakartaee.servlet.servlet.
  • If your previous project is still using javax.servlet. servlet, your project cannot be deployed directly to the Tomcat10+ release. You can only deploy to Tomcat9- version. The javax.servlet package is still recognized in Versions of Tomcat9 and before.

Fixed Tomcat server garble in DOS command window (console garble)

Will the CATALINA_HOME/conf/logging. The content change in the properties file is as follows:

java.util.logging.ConsoleHandler.encoding = GBK

Respond to the browser with a piece of HTML code

public void service(ServletRequest request, ServletResponse response){
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.print("

hello servlet!

"
); } Copy the code

How do I connect to a database in a Servlet?

  • Servlets are Java programs, so it’s perfectly possible to write JDBC code to connect to a database in a Servlet.
  • To connect to a database in a WebApp, place the driver JAR package in the WEB-INF/lib directory. (The com.mysql.cj.jdbc.driver class is included in the Driver JAR package.)

Develop Servlet applications in an integrated development environment

  • There are many integrated development tools, among which the most commonly used are:

    • IntelliJ IDEA (this is mostly, IDEA is better than Eclipse in the prompt function, that is, IDEA is smarter than Eclipse to use, better use. JetBrain. For a fee.)
    • Eclipse (this is less), Eclipse is still used by teams, but in a decreasing trend, after doing their own work, you may encounter. Eclipse was developed by the IBM team. Eclipse means “Eclipse”. “Eclipse” means eat the sun. The SUN is the SUN. The IBM team developed Eclipse as a way to swallow SUN, which was acquired by Oracle in 2009. IBM did not succeed in acquiring SUN.
  • Develop servlets using the IDEA integrated development tool

    • First step: New Project (I prefer to create an Empty Project first and then create a Module under the Empty Project, this is not necessary, just a habit, you can directly create a non-empty Project). This Empty Project is called: Javaweb (not required, just a name. In general, the name of the new Project should be the same as the name of the directory.
    • Step 2: Create a new Module (File –> new –> Module…)
      • What you create here is a normal JavaSE module (don’t create a Java Enterprise module here yet)
      • This Module is automatically placed under the JavaWeb project.
      • This Module is named servlet01
    • Step 3: make the Module a JavaEE Module. Make Module a webApp Module. Conforms to webApp specifications. Servlet compliant Module)
      • Right-click on Module: Add Framework Support… (Added framework support)
      • In the window that pops up, select Web Application (WebApp support is selected)
      • After selecting webApp support, IDEA will automatically generate a WebPP directory structure for you that conforms to the Servlet specification.
      • Important, note: In the directory generated from the Web Application template in the IDEA tool, there is a Web directory, which represents the root of webApp
    • Step 4 (optional) : There is an index.jsp file in the resource generated from the Web Application. Here I choose to delete the index.jsp file.
    • Step 5: Write a Servlet (StudentServlet)
      • class StudentServlet implements Servlet
      • The servlet.class file is not available at this point. How to do? Add CATALINA_HOME/lib/servlet-api.jar and jsp-api.jar to your classpath.
        • File –> Project Structrue –> Modules –> + plus –> Add JARS….
      • Implement 5 methods in Jakarta.Servlet.Servlet interface.
    • Step 6: Write the business code in the Service method in the Servlet (we’re connecting to the database here).
    • Step 7: Create a new subdirectory in the WEB-INF directory: lib (this directory name should be all lowercase lib) and put the jar package connected to the database in the lib directory.
    • Step 8: Register the StudentServlet class in the web. XML file. (Mapping between request paths and servlets)
    <? xml version="1.0" encoding="UTF-8"? > <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
             version="4.0">
    
        <servlet>
            <servlet-name>studentServlet</servlet-name>
            <servlet-class>com.bjpowernode.javaweb.servlet.StudentServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>studentServlet</servlet-name>
            <url-pattern>/servlet/student</url-pattern>
        </servlet-mapping>
        
    </web-app>
    Copy the code
    • Step 9: Give an HTML page, write a hyperlink in the HTML page, the user clicks the hyperlink, sends the request, Tomcat executes the backend StudentServlet.

      • student.html

      • This file cannot be placed in the WEB-INF directory, only outside the web-INF directory.

      • The contents of the student.html file

      • <! DOCTYPEhtml>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>student page</title>
        </head>
        <body>
            <! < span style = "max-width: 100%; clear: both; min-height: 1em;
            <a href="/xmm/servlet/student">student list</a>
        </body>
        </html>
        Copy the code
    • Step 10: Have the IDEA tool disassociate the Tomcat server. Deploy the WebApp to the Tomcat server during the association process.

      • In the upper right corner of the IDEA tool, there is Add Configuration on the right of the green hammer
      • Top left plus sign, click Tomcat Server –> local
      • Set Server parameters in the popup interface (basically do not move)
      • There is a Deployment in the current window (click on this to deploy webApp), and click on the plus sign to deploy.
      • Change the Application Context to: / XMM
    • Step 11: Start the Tomcat server

      • There is a green arrow or a green bug in the upper right corner. Click the green bug to start the Tomcat server in debug mode.
      • It is recommended to start Tomcat in debug mode during development
    • Step 12: open a browser and input on the browser’s address bar: http://localhost:8080/xmm/student.html

The life cycle of a Servlet object

  • What is the Servlet object life cycle?

    • When the Servlet object is created.
    • When the Servlet object is destroyed.
    • How many Servlet objects are created?
    • The life cycle of a Servlet object represents how a Servlet object works from birth to death.
  • Who maintains Servlet objects?

    • The Javaweb programmer has no right to interfere with the creation of Servlet objects, the invocation of methods on objects, and the eventual destruction of objects.
    • The life cycle of Servlet objects is the sole responsibility of the Tomcat Server (WEB Server).
    • The Tomcat server is often referred to as the WEB container. (You need to know WEB Container.)
    • WEB containers to manage the life and death of Servlet objects.
  • Consider: Are our new Servlet objects managed by the WEB container?

    • Our own Servlet object for New is not managed by the WEB container.
    • Servlet objects created by the WEB container are put into a collection (HashMap), and only servlets put into the HashMap collection can be managed by the WEB container. Servlet objects new by themselves are not managed by the WEB container. (Own new Servlet object is not in the container)
    • The Underlying Web container should have a collection such as a HashMap that stores the relationship between Servlet objects and request paths
  • Research: are Servlet objects created for server startup (by default)?

    • Provide a no-argument constructor in the Servlet and start the server to see if the constructor executes.
    • By default, Servlet objects are not instantiated when the server is started.
    • The design is reasonable. Creating all of the Servlet objects before the user sends the request would cost memory, and if the Servlet object is never accessed by the user, it is obvious that the Servlet object is useless and does not need to be created in the first place.
  • How do I create Servlet objects when the server starts up?

    • Add a sublabel to the servlet label and fill in the sublabel with an integer, the smaller the integer, the higher the priority.

    • <servlet>
          <servlet-name>aservlet</servlet-name>
          <servlet-class>com.bjpowernode.javaweb.servlet.AServlet</servlet-class>
          <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
          <servlet-name>aservlet</servlet-name>
          <url-pattern>/a</url-pattern>
      </servlet-mapping>
      Copy the code
  • Servlet object life cycle

    • By default, the AServlet object is not instantiated when the server starts

    • When the user sends the first request, the console outputs the following:

      The AServlet no-argument constructor executes AServlet's init method execute! AServlet's service method execute!Copy the code
    • Conclusions can be drawn from the above output contents:

      • The Servlet object is instantiated when the user sends the first request (the constructor of AServlet is executed). And the no-argument constructor is performed.
      • As soon as the AServlet object is created, the Tomcat server calls the init method of the AServlet object. The AServlet object already exists when the init method is executed. It’s already created.
      • When the user sends the first request, the Tomcat server calls the service method of the AServlet object immediately after the init method is executed.
    • The user continues to send the second request, and the console outputs the following:

      AServlet's service method execute!
      Copy the code
    • According to the above output results, when the user sends the second, third, or fourth request, the Servlet object is not newly created, but still uses the previously created Servlet object to directly call the service method of the Servlet object, which indicates:

      • First: Servlet objects are singleton (singleton). Note, however, that Servlet objects are singleton, whereas Servlet classes do not conform to the singleton pattern. We call this a false singleton. The reason for the singleton is that Servlet object creation is beyond the control of JavaWeb programmers. Tomcat only creates one object, which results in a singleton, but it is a fake singleton. True singleton, the constructor is private.
      • Second: the no-argument constructor, init, is executed only the first time the user sends the request. That is, the no-argument constructor is executed only once. The init method is also called only once by the Tomcat server.
      • Third: As long as the user sends a request: the service method must be called once by the Tomcat server. The service method will be called 100 times after 100 requests are sent.
    • When the server is shut down, the console outputs the following:

      AServlet's destroy method execute!
      Copy the code
    • Based on the above output, the following conclusions can be drawn:

      • The Servlet’s destroy method is called only once by the Tomcat server.
      • When was the destroy method called?
        • When the server is down.
        • Because the memory of the AServlet object is destroyed when the server shuts down.
        • Before the server destroys the memory of the AServlet object, the Tomcat server automatically calls the destroy method of the AServlet object.
    • Is the object destroyed or not destroyed when the destroy method is called?

      • The destroy method executes while the AServlet object is still there and not destroyed. After the destroy method completes, the memory of the AServlet object is freed by Tomcat.
    • Servlet objects are more like a person’s life:

      • Servlet’s no-argument constructor executes: signals you were born.
      • Execution of init methods on Servlet objects: a sign that you are getting an education.
      • The execution of the Service method on a Servlet object: it signals that you are ready to work and provide a service to humans.
      • Execution of the destroy method on the Servlet object: marks the end. Any last words? Hold on tight. Otherwise, it’s too late.
    • How many times are methods called in the Servlet class?

      • The constructor is executed only once.
      • The init method is executed only once.
      • Service method: The service is executed once when the user sends one request, and N times when the user sends N requests.
      • The destroy method is executed only once.
    • When we write a constructor with parameters in our Servlet class, what happens if we don’t write a parameterless constructor by hand?

      • Error: 500 error.
      • Note: 500 is an HTTP protocol error status code.
      • 500 Usually because the Java program on the server is abnormal. (All server-side errors are error 500: server internal errors.)
      • The absence of a parameterless constructor results in a 500 error and the Servlet object cannot be instantiated.
      • Therefore, it is important to note that in Servlet development, programmers are not advised to define constructors, because if they are not properly defined, they may not be able to instantiate Servlet objects.
    • Consider: A Servlet’s no-argument constructor is executed when the object is first created, and only once. The init method is also executed when the object is first created and only once. So can this no-argument constructor replace init?

      • Can’t.
      • The Servlet specification states that as a javaweb programmer writing a Servlet class, it is not recommended to write a constructor by hand, because it is easy to write a constructor without arguments, which may cause the Servlet object to fail to be instantiated. So the init method is necessary.
    • Which method is most used among init, service, and destroy?

      • The most commonly used method is the Service method, which must be implemented because it is the core method for handling user requests.
      • When do you use the init method?
        • The init method is rarely used.
        • Initialization is usually done in the init method, and it only needs to be done once. Example: initialize the database connection pool, initialize the thread pool….
      • When do you use the destroy method?
        • The destroy method is also rarely used.
        • The resource is usually closed in the destroy method. Object will be destroyed soon, there is any not closed, close resources as soon as possible. What resources have not been saved, seize the time to save.

GenericServlet

  • What are the disadvantages of writing a Servlet class that directly implements the Servlet interface?

    • We only need the service method; most of the other methods are not needed. The code is ugly.
  • Adapter design pattern Adapter

    • The mobile phone is directly inserted into the voltage of 220V, the mobile phone is scrapped directly. How to do? Find a charger. The charger is an adapter. Cell phone connection adapter. The adapter is connected to 220V voltage. That solves the problem.
  • Write a GenericServlet class that is an abstract class with an abstract method service.

    • GenericServlet implements the Servlet interface.
    • GenericServlet is an adapter.
    • All Servlet classes written later inherit GenericServlet and simply override the Service method.
  • Question to consider: Does the GenericServlet class need a makeover? How? Better for subclassing, right?

    • Consider the first question: will the init method still execute after I provide a GenericServlet?

      • It will be executed. The init method in the GenericServlet class is executed.
    • Consider the second question: who calls the init method?

      • Tomcat server call.
    • Consider the third question: Who created the ServletConfig object in the init method? Who sent it?

      • It’s all Tomcat.
      • The Tomcat server creates the ServletConfig object and then calls the init method, passing the ServletConfig object to the init method.
    • Consider the Tomcat server pseudocode:

      • public class Tomcat {
            public static void main(String[] args){
                / /...
                // Tomcat server pseudocode
                // Create the LoginServlet object (instantiate the LoginServlet object by calling the no-argument constructor via reflection)
                Class clazz = Class.forName("com.bjpowernode.javaweb.servlet.LoginServlet");
                Object obj = clazz.newInstance();
                
                // Downward transition
                Servlet servlet = (Servlet)obj;
                
                // Create a ServletConfig object
                // The Tomcat server is responsible for instantiating the ServletConfig object.
                // Polymorphic (Tomcat server fully implements the Servlet specification)
                ServletConfig servletConfig = new org.apache.catalina.core.StandardWrapperFacade();
                
                // Call the init method of the Servlet
                servlet.init(servletConfig);
                
                // Call the Servlet's service method
                / /...}}Copy the code

ServletConfig

  • What is ServletConfig?

    • Configuration information object for the Servlet object.
    • The configuration information in the tag is encapsulated in the ServletConfig object. (Configuration information for the servlet in the web.xml file)
  • A Servlet corresponds to a ServletConfig object.

  • The Servlet object is created by the Tomcat server, and the ServletConfig object is also created by the Tomcat server. And by default, they are created when the user sends the first request.

  • When the Tomcat server calls the init method of the Servlet object, it needs to pass a ServletConfig object parameter to the init method.

  • The ServletConfig interface implementation class is implemented by the Tomcat server. (A Tomcat server is a WEB server.)

  • What are the common methods of the ServletConfig interface?

    • public String getInitParameter(String name); // Get value by initializing the parameter name
      public Enumeration<String> getInitParameterNames(a); // Get the names of all initialization parameters
      public ServletContext getServletContext(a); // Get the ServletContext object
      public String getServletName(a); // Get the Servlet's name
      Copy the code
    • All of the above methods can be called using this in the Servlet class. Because GenericServlet implements the ServletConfig interface.

ServletContext

  • A Servlet object corresponds to a ServletConfig. For 100 Servlet objects, there are 100 ServletConfig objects.

  • All Servlet objects share the same ServletContext object as long as they are in the same WebApp, as long as they are in the same application.

  • The ServletContext object is created during server startup and destroyed when the server is shut down. This is the life cycle of the ServletContext object. The ServletContext object is an application-level object.

  • The Tomcat server has a Webapp, and this webapp can store webApps, and it can store multiple WebApps. If there are 100 WebApps, then there are 100 ServletContext objects. But, anyway, an application, a WebApp must only have one ServletContext object.

  • A ServletContext is called a Servlet context object. (The surrounding environment object of the Servlet object.)

  • A ServletContext object typically corresponds to a web.xml file.

  • What example of life does the ServletContext correspond to?

    • If there are multiple students in a classroom, each student is a Servlet, and they are all in the same classroom, we can call this classroom a ServletContext object. So what that means is that the data that you put in this ServletContext object, the objects are shared in the same classroom. For example, there is an air conditioner in the classroom that all the students can operate. Visible, air conditioning is shared. Because the air conditioner is in the classroom. The classroom is the ServletContext object.
  • ServletContext is an interface implemented by the Tomcat server.

    • The creation of the ServletContext object is also done by the Tomcat server. Created when you start webApp.
  • What are the common methods in the ServletContext interface?

    • public String getInitParameter(String name); // Get value by initializing the parameter name
      public Enumeration<String> getInitParameterNames(a); // Get the names of all initialization parameters
      Copy the code
    • <! These two methods are methods of the ServletContext object. What information does this method get? Is the following configuration information -->
      <context-param>
          <param-name>pageSize</param-name>
          <param-value>10</param-value>
      </context-param>
      <context-param>
          <param-name>startIndex</param-name>
          <param-value>0</param-value>
      </context-param>
      <! Note: The preceding configuration information is application-level configuration information. Generally, the configuration information shared in a project is added to the preceding labels. -->
      <! If your configuration information is intended for reference only to a servlet, then you can configure it in the servlet tag, using the ServletConfig object. -->
      Copy the code
    • // Get the root path of the application (very important), because there are places in the Java source code where the root path of the application may be needed, this method can dynamically get the root path of the application
      // In Java source code, do not write the root path of the application dead, because you never know what the application will be called when it is finally deployed.
      public String getContextPath(a);
      //String contextPath = application.getContextPath();
      Copy the code
    • // Get the absolute path of the file (real path)
      public String getRealPath(String path);
      Copy the code
    • // Logging is also possible through the ServletContext object
      public void log(String message);
      public void log(String message, Throwable t);
      // Where is the log information recorded?
      // localhost.2021-11-05.log
      
      // What are the log files in the logs directory of the Tomcat server?
      // Catalina.2021-11-05.log Console information about Java programs running on the server.
      // Localhost. 2021-11-05.log Logs recorded by the log method of the ServletContext object are stored in this file.
      //localhost_access_log.2021-11-05.txt Access logs
      Copy the code
    • // The ServletContext object has another name: application domain (there will be other fields later, such as request domain, session domain)
      
      // If all users share a piece of data, the data is rarely modified, and the data volume is small, you can put the data into the ServletContext application
      
      // Why is the data shared by all users? Not shared is meaningless. Because there's only one ServletContext object. It only makes sense to put shared data in.
      
      // Why is the data volume small? Because a large amount of data takes up too much heap memory, and the object has a long life cycle, the object will be destroyed when the server is shut down. Large amounts of data affect server performance. The amount of data that occupies less memory can be considered.
      
      // Why is this shared data rarely or never modified?
      // If the data shared by all users is modified, there will be security problems caused by concurrent threads. So the data placed in the ServletContext object is generally read-only.
      
      // The amount of data is small, shared by all users, and not modified. Putting such data into the application domain ServletContext can greatly improve efficiency. Because an application domain serves as a cache, data stored in the cache does not need to be retrieved from the database for next use, greatly improving execution efficiency.
      
      // Save (how to save data to ServletContext)
      public void setAttribute(String name, Object value); // map.put(k, v)
      // Fetch (how to fetch data from ServletContext)
      public Object getAttribute(String name); // Object v = map.get(k)
      // Delete (how to delete data in ServletContext)
      public void removeAttribute(String name); // map.remove(k)
      
      
      Copy the code
  • Note: In the future, when we write Servlet classes, we will not inherit GenericServlet directly, because we are a B/S system based on HTTP hypertext transfer protocol. In the Servlet specification, we provide a class called HttpServlet. It is a Servlet class designed specifically for the HTTP protocol. The Servlet class we write inherits HttpServlet. (Httpservlets are HTTP protocol specific.) It is easier to use Httpservlets to handle HTTP. But you need to get down to its inheritance structure:

    • The Jakarta. Servlet. Servlet (interface) "grandpa" Jakarta. Servlet. GenericServlet implements the servlet class (abstract) "son" Jakarta. Servlet. HTTP. HttpServlet extends GenericServlet class (abstract) after our grandson 】 【 write servlet to inherit the HttpServlet class.Copy the code
  • What caching mechanisms have you been exposed to so far?

    • Pool of string constants in heap memory.
      • “ABC” is first looked up in the string constant pool, if any, directly used. If not, create a new one and add it to the string constant pool.
    • A pool of integer constants in heap memory.
      • [-128 to 127] A total of 256 Integer references are stored in the Integer constant pool. If you don’t go beyond that range, you get it directly from the constant pool.
    • Connection Cache
      • The connections in the Connection pool in question are the Java language Connection objects to the database: java.sql.Connection objects.
      • The JVM is a process. MySQL database is a process. It is laborious to establish connections between processes and open channels. It’s very resource-intensive. How to do? We can create N Connection objects in advance and put them into a collection, which we call a Connection pool. Each time a user connects, the connection object is directly obtained from the connection pool, which greatly improves the access efficiency.
      • The connection pool
        • Minimum number of connections
        • Maximum number of connections
        • Connection pooling improves user access efficiency. Of course, it can also ensure the security of the database.
    • The thread pool
      • The Tomcat server itself supports multithreading.
      • Does the Tomcat server create a Thread object every time the user sends a request?
        • Of course not. In fact, when the Tomcat server starts up, it creates more than N Thread objects, and then puts them into a collection called Thread pool. When a user sends a request, a thread needs to process the request, and the thread object is taken directly from the thread pool, which is more efficient.
        • All WEB servers, or application servers, are multithreaded and have thread pools.
    • redis
      • NoSQL database. Non-relational databases. Cache the database.
    • Storing data in the ServletContext application domain also stores the data in the cache cache.

The HTTP protocol

  • What is an agreement?

    • An agreement is actually a set of norms developed by some people or some organizations in advance, and we all follow this norm, so that we can achieve barrier-free communication.
    • An agreement is a set of norms, a set of standards. It’s made by other people or other organizations.
    • You can understand what I say, and I can understand what you say, which shows that there is a set of norms and a set of agreements between us, which is the Chinese Mandarin agreement. We all follow this protocol, so we can communicate without obstacles.
  • What is the HTTP protocol?

    • HTTP protocol: A hypertext transfer protocol developed by the W3C. (Communication protocols: Templates for sending messages are made in advance.)
    • The W3C:
      • World Wide Web Consortium
      • Responsible for the formulation of standards: HTTP HTML4.0, HTML5, XML, DOM and other specifications are formulated by W3C.
      • Father of the World Wide Web: Tim Berners-Lee
    • What is hypertext?
      • Hypertext is not normal text, like streaming media: sound, video, pictures, etc.
      • HTTP: supports the transmission of common character strings as well as streaming media such as sound, video, and picture.
    • This protocol walks between B and S. B sends data to S following the HTTP protocol. S sends data to B using HTTP. So that B and S can be decoupled.
    • What is uncoupling?
      • B doesn’t depend on S.
      • S does not depend on B.
    • B/S: A B/S structured system (a system where a browser accesses a WEB server)
    • The browser sends data to the WEB server, called a request.
    • The WEB server sends data to the browser, called a response.
    • HTTP protocols include:
      • Request protocol
        • When a browser sends data to a WEB server, the data sent must follow a set of standards that specify the format of the data sent.
      • Response protocol
        • When a WEB server sends data to a browser, the data it sends needs to follow a set of standards that specify the format of the data it sends.
    • The HTTP protocol is a message template that has been written out in advance.
      • It doesn’t matter what brand of browser you are.
      • It doesn’t matter what brand of WEB server you are.
      • The FF browser can send requests to Tomcat as well as to the Jetty server. Browsers are not dependent on specific server brands.
      • WEB servers are also independent of specific browser brands. It could be FF, it could be Chrome, it could be Internet Explorer, whatever.
  • HTTP request protocol (B –> S)

    • The HTTP request protocol consists of the following four parts

      • The request line
      • Request header
      • Blank lines
      • Request body
    • HTTP request packet: GET request

      • GET /servlet05/getServlet? Username = lucy&userPwd =1111 HTTP/1.1 Request line Host: localhost:8080 Request header Connection: keep-alive sec-CH-ua: "Google Chrome"; v="95", "Chromium"; v="95", "; Not A Brand"; v="99" sec-ch-ua-mobile: ? 0 sec-CH-UA-platform: "Windows" upgrade-insecure -Requests: 1 User-agent: Mozilla/5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml; Q = 0.9, image/avif, image/webp image/apng, * / *; Q = 0.8, application/signed - exchange; v=b3; Q =0.9 sec-fetch -Site: same-origin SEC-fetch -Mode: navigate sec-fetch -User:? 1 Sec-Fetch-Dest: document Referer: http://localhost:8080/servlet05/index.html Accept-Encoding: gzip, deflate, br Accept-Language: zh-CN,zh; Q =0.9 Blank line request bodyCopy the code
    • HTTP request packet: POST request

      • POST/Servlet05 /postServlet HTTP/1.1 Request line Host: localhost:8080 Request header Connection: keep-alive Content-Length: 25 Cache-Control: max-age=0 sec-ch-ua: "Google Chrome"; v="95", "Chromium"; v="95", "; Not A Brand"; v="99" sec-ch-ua-mobile: ? 0 sec-ch-ua-platform: "Windows" Upgrade-Insecure-Requests: 1 Origin: http://localhost:8080 Content-Type: Application/X-www-form-urlencoded User-agent: Mozilla/5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml; Q = 0.9, image/avif, image/webp image/apng, * / *; Q = 0.8, application/signed - exchange; v=b3; Q =0.9 sec-fetch -Site: same-origin SEC-fetch -Mode: navigate sec-fetch -User:? 1 Sec-Fetch-Dest: document Referer: http://localhost:8080/servlet05/index.html Accept-Encoding: gzip, deflate, br Accept-Language: zh-CN,zh; Q =0.9 Blank line username= Lisi&userPwd =123 Request bodyCopy the code
    • The request line

      • It consists of three parts:
        • Part I: Request Methods (7)
          • Get (used)
          • Post (commonly used)
          • delete
          • put
          • head
          • options
          • trace
        • Part 2: URI
          • What is a URI? Uniform Resource Identifier (URI). Represents the name of a resource on the network. However, resources cannot be located through URIs.
          • What is a URL? Uniform resource locator. Represents a resource on the network and can be located by the URL.
          • What’s the difference between a URI and a URL?
            • URL including the URI
            • http://localhost:8080/servlet05/index.html this is the URL.
            • /servlet05/index.html This is the URI.
        • Part three: HTTP protocol version number
    • Request header

      • Requested host
      • Host port
      • Browser information
      • Information platform
      • The information such as cookies,
      • .
    • Blank lines

      • The blank line is used to distinguish the “request header” from the “request body”
    • Request body

      • Specific data sent to the server.
  • HTTP response protocol (S -> B)

    • The HTTP response protocol consists of the following four parts

      • The status line
      • Response headers
      • Blank lines
      • Response body
    • Specific HTTP response packets:

      • HTTP/1.1 200 OK Status line Content-Type: text/ HTML; Charset =UTF-8 Response header Content-Length: 160 Date: Mon, 08 Nov 2021 13:19:32 GMT KEEP-alive: timeout=20 Connection: Keep-alive blank line <! Doctype HTML > response body < HTML > <head> <title>from get servlet</title> </head> <body> <h1> From get servlet</h1> </body> </ HTML >Copy the code
    • The status line

      • Three parts
        • Part I: Protocol Version Number (HTTP/1.1)
        • Part two: Status code (the response status number specified in the HTTP protocol. Different response results correspond to different numbers.
          • 200 indicates that the request response is successful.
          • 404 indicates that the requested resource does not exist, usually because you either wrote the wrong path or the correct path, but the corresponding resource on the server did not start successfully. The 404 error is a front-end error.
          • 405 indicates that the request mode sent by the front-end is inconsistent with the processing mode of the back-end request:
            • For example, when the front-end is a POST request and the back-end is processed in GET mode, 405 occurs
            • For example, if the front-end is a GET request and the back-end is a POST request, 405 occurs
          • 500 indicates that the program on the server side is abnormal. It is generally assumed that this is caused by a server-side error.
          • Starts with a 4, usually due to a browser error.
          • Those starting with 5 are usually caused by server-side errors.
        • Part three: Description of the status
          • Ok indicates that the operation succeeds.
          • Not found Indicates that the resource cannot be found.
    • Header:

      • The content type of the response
      • The content length of the response
      • Response time
      • .
    • Blank lines:

      • Used to separate response header from response body.
    • Response body:

      • The body of the response is the body of the response, which is a long string that is rendered, interpreted, and executed by the browser to display the effect.
  • How to view the content of the protocol?

    • Use Chrome: F12. Then go to network and view the details of the protocol through this panel.
  • How do I send a GET request to the server, how do I send a POST request to the server?

    • So far, there is only one way to send a POST request: use a form and the method attribute in the form tag has a value of method=” POST “.
    • All other cases are uniformly GET requests:
      • Enter the URL in the browser address bar and press Enter. This is a GET request.
      • Clicking a hyperlink on the browser is a GET request.
      • When submitting data using the form form, there is no method attribute in the form tag. The default is GET
      • Or when you use a form, the value of the method attribute in the form tag is method=”get”.
      • .
  • What is the difference between a GET request and a POST request?

    • When a GET request sends data, the data is attached to the URI and a “? “is appended to the URI. , “?” And then the data. This will cause the sent data to be displayed in the browser address bar. (GET requests send data on the “request line”)
      • http://localhost:8080/servlet05/getServlet?username=zhangsan&userpwd=1111
    • When a POST request sends data, it sends it in the body of the request. Does not echo to the browser address bar. That is, the data sent by post is not visible in the browser address bar. (Post sends data in the “request body”)
    • Get requests can only send plain strings. And there is a limit to the length of the string to be sent, which varies from browser to browser. There is no clear specification for this.
    • Get requests cannot send large amounts of data.
    • Post requests can send any type of data, including ordinary strings, and streaming media information: video, sound, and picture.
    • Post requests can send large amounts of data and theoretically have no length limit.
    • Get requests are better suited for retrieving data from the server side.
    • Post requests are better suited for sending data to the server side, as described in the W3C.
    • Get requests are secure. Get requests are perfectly secure. Why is that? Because the GET request is just to get data from the server. There is no threat to the server. Get is inherently safe. Don’t use it wrong. It’s your fault, not the get request.
    • Post requests are dangerous. Why is that? Because a POST request is a submission of data to the server, the server can be dangerous if the data gets into the server through the back door. In addition, post is to submit data, so in general, when intercepting requests, most will choose to intercept (listen for) POST requests.
    • Get requests support caching.
      • N.s inaimg. Cn/finance / 590…
      • The final “response result” of any GET request is cached by the browser. In the browser cache:
        • Path A of a GET request corresponds to a resource.
        • A GET request path B corresponds to a resource.
        • A get request path C corresponds to a resource.
        • .
      • In fact, whenever you send a GET request, the first thing the browser does is look for it in the local browser cache, and when it can’t find it, it goes to the server to get it. The purpose of this caching mechanism is to improve the user experience.
      • Is there a requirement that we don’t want get requests to go out of the cache? How to avoid caching? I want every get request to go to the server to find the resource, I don’t want to fetch it from the local browser cache.
        • As long as the request path is different for each GET request.
        • N.s inaimg. Cn/finance / 590…
        • N.s inaimg. Cn/finance / 590…
        • N.s inaimg. Cn/finance / 590…
        • How to solve it? You can add a “time stamp” to the end of the path that changes from moment to moment, so that each request path is different and the browser does not use the cache.
    • Post requests do not support caching. (POST is used to modify resources on the server side.)
      • After a POST request, the server’s “response result” is not cached by the browser. Because this cache doesn’t make sense.
  • How do I choose between GET and POST requests, and when do I use GET and when do I use POST?

    • How do I choose between GET and POST requests? What is the measure? Do you want to fetch data from the server, or do you want to send data to the server? If you want to GET a resource from the server, use a GET request. If you want to submit data to the server, use a POST request.
    • Most forms are submitted by POST, because a large amount of data needs to be filled in the form, which collects user information and generally needs to be sent to the server, which saves/modifies the data and so on.
    • If there is sensitive information in the form, it is recommended to use the POST request because the GET request will return sensitive information to the browser address bar. (For example, password information)
    • Do file upload, must be a POST request. The data to be passed is not plain text.
    • Get requests can be used in all other cases.
  • Whether you make a GET request or a POST request, the format of the sent request data is exactly the same, but in different locations:

    • name=value&name=value&name=value&name=value
    • What is name?
      • Take the form form as an example: The name of the input tag in the form form.
    • What is value?
      • Take the form form for example: The value of the input tag in the form form.

Template method design patterns

  • What are design patterns?
    • A fixed solution to a problem. (It can be reused.)
  • What design patterns do you know?
    • GoF design mode:
      • Usually what we call 23 design patterns. (Design Patterns proposed by the Gang of Four)
      • The singleton pattern
      • The factory pattern
      • The proxy pattern
      • Facade pattern
      • Chain of responsibility design patterns
      • Observer model
      • Template method design patterns
      • .
    • JavaEE design pattern:
      • DAO
      • DTO
      • VO
      • PO
      • pojo
      • .
    • .
  • What is the template method design pattern?
    • The core algorithm skeleton is defined in the template method of the template class, and the implementation steps can be deferred to the subclass.
  • A template class is usually an abstract class. The template method in the template class defines the core algorithm. This method is usually final (but may not be final)
  • An abstract method in a template class is a method whose implementation is uncertain, leaving it to subclasses to implement.

HttpServlet source code analysis

  • The HttpServlet class is designed specifically for the HTTP protocol. More suitable for HTTP development than GenericServlet.
  • Which package is the HttpServlet under?
    • jakarta.servlet.http.HttpServlet
  • What interfaces in the servlet specification have we touched on so far?
    • Jakarta.servlet.Servlet core interface (interface)
    • Jakarta. Servlet. ServletConfig servlet configuration information interface (interface)
    • The Jakarta. Servlet. ServletContext servlet context interface (interface)
    • The Jakarta. Servlet. ServletRequest servlet request interface (interface)
    • The Jakarta. Servlet. ServletResponse servlet response interface (interface)
    • Jakarta. Servlet. ServletException servlet exception (class)
    • Jakarta. Servlet. GenericServlet standard general servlet class (abstract)
  • What are the classes and interfaces under the HTTP package? jakarta.servlet.http.*;
    • The Jakarta. Servlet. HTTP. HttpServlet (HTTP protocol dedicated servlet class, abstract class)
    • The Jakarta. Servlet. HTTP. It (for HTTP protocol, the request object)
    • The Jakarta. Servlet. HTTP. HttpServletResponse (for HTTP protocol, the response object)
  • What information is encapsulated in the HttpServletRequest object?
    • HttpServletRequest, or request object.
    • HttpServletRequest encapsulates the entire content of the request protocol.
    • The Tomcat server (WEB server) parses all the data in the Request protocol and encapsulates it all in the Request object.
    • That is, we can get the data in the request protocol simply by facing HttpServletRequest.
  • The HttpServletResponse object is designed to respond to the HTTP protocol to the browser.
  • Recall the Servlet life cycle?
    • First request from the user
      • The Tomcat server invokes the no-argument constructor through reflection. Create a Servlet object. (The object corresponding to the Servlet class configured in the web.xml file.)
      • The Tomcat server calls the init method of the Servlet object to complete initialization.
      • The Tomcat server calls the Service method of the Servlet object to process the request.
    • The user made the second request
      • The Tomcat server calls the Service method of the Servlet object to process the request.
    • The user made the third request
      • The Tomcat server calls the Service method of the Servlet object to process the request.
    • .
      • The Tomcat server calls the Service method of the Servlet object to process the request.
    • Server Shutdown
      • The Tomcat server calls the destroy method on the Servlet object to prepare it for destruction.
      • The Tomcat server destroys the Servlet object.
  • HttpServlet source code:
public class HelloServlet extends HttpServlet {
	// This no-argument constructor is executed the first time the user requests the HelloServlet object to be created.
	public HelloServlet(a) {}//override overrides the doGet method
    Override overrides the doPost method
}

public abstract class GenericServlet implements Servlet.ServletConfig.java.io.Serializable {
           
	// This init method is executed after the HelloServlet object is first created when the user first requests it.
    public void init(ServletConfig config) throws ServletException {
        this.config = config;
        this.init();
    }
	// Init () with no arguments is executed after init(ServletConfig config) is executed when the user first requests it.
	public void init(a) throws ServletException {
        // NOOP by default}}// HttpServlet template class.
public abstract class HttpServlet extends GenericServlet {
    // This service is executed when the user sends the first request
    // When the user sends the NTH request, the service method is still executed.
    // Once the user sends a request, the service method executes once.
    @Override
    public void service(ServletRequest req, ServletResponse res)
        throws ServletException, IOException {

        HttpServletRequest  request;
        HttpServletResponse response;

        try {
            // Transition ServletRequest and ServletResponse downward to HttpServletRequest and HttpServletResponse with Http
            request = (HttpServletRequest) req;
            response = (HttpServletResponse) res;
        } catch (ClassCastException e) {
            throw new ServletException(lStrings.getString("http.non_http"));
        }
        // Call the overloaded service method.
        service(request, response);
    }
    
    // Both parameters of this service method are Http.
    // This service is a template method.
    // In this method, the core algorithm skeleton is defined, and the concrete implementation steps are deferred to the subclass.
    protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
        // Get the request mode
        // This request may end up being: ""
        // Note: the request.getMethod() method gets the request method, which may be one of seven:
        // GET POST PUT DELETE HEAD OPTIONS TRACE
        String method = req.getMethod();

        // If the request is a GET request, the doGet method is executed.
        if (method.equals(METHOD_GET)) {
            long lastModified = getLastModified(req);
            if (lastModified == -1) {
                // servlet doesn't support if-modified-since, no reason
                // to go through further expensive logic
                doGet(req, resp);
            } else {
                long ifModifiedSince;
                try {
                    ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
                } catch (IllegalArgumentException iae) {
                    // Invalid date header - proceed as if none was set
                    ifModifiedSince = -1;
                }
                if (ifModifiedSince < (lastModified / 1000 * 1000)) {
                    // If the servlet mod time is later, call doGet()
                    // Round down to the nearest second for a proper compare
                    // A ifModifiedSince of -1 will always be less
                    maybeSetLastModified(resp, lastModified);
                    doGet(req, resp);
                } else{ resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); }}}else if (method.equals(METHOD_HEAD)) {
            long lastModified = getLastModified(req);
            maybeSetLastModified(resp, lastModified);
            doHead(req, resp);

        } else if (method.equals(METHOD_POST)) {
            // Execute the doPost method if the request is a POST request.
            doPost(req, resp);

        } else if (method.equals(METHOD_PUT)) {
            doPut(req, resp);

        } else if (method.equals(METHOD_DELETE)) {
            doDelete(req, resp);

        } else if (method.equals(METHOD_OPTIONS)) {
            doOptions(req,resp);

        } else if (method.equals(METHOD_TRACE)) {
            doTrace(req,resp);

        } else {
            //
            // Note that this means NO servlet supports whatever
            // method was requested, anywhere on this server.
            //

            String errMsg = lStrings.getString("http.method_not_implemented");
            Object[] errArgs = new Object[1];
            errArgs[0] = method; errMsg = MessageFormat.format(errMsg, errArgs); resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg); }}protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException{
        // Error 405 is reported
        String msg = lStrings.getString("http.method_get_not_supported");
        sendMethodNotAllowed(req, resp, msg);
    }
    
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
        // Error 405 is reported
        String msg = lStrings.getString("http.method_post_not_supported"); sendMethodNotAllowed(req, resp, msg); }}/* If the request sent by the front end is a GET request and the method overwritten by the back end is doPost, what happens if the request sent by the front end is a POST request and the method overwritten by the back end is doGet? An error such as 405 occurred. 405 indicates a front-end error. The request is sent in the wrong way. Inconsistent with the server. Not the way the server requests it. As you can see from the above source code: whenever the doGet or doPost methods in the HttpServlet class are executed, 405 must be required. How do you avoid the 405 error? The backend rewrites the doGet method, and the front-end must send get requests. The doPost method is rewritten on the back end, and the front end must send a POST request. This avoids the 405 error. It's up to the back end to decide what kind of requests the front-end needs to make. The front end has to do what the back end tells it to do. Some of you will see that the doGet and doPost methods are overwritten in the Servlet class to avoid 405 errors. In this way, the 405 error can be avoided, but it is not recommended that the 405 error be useful. When the paper is wrong, you should let him report it. If you overwrite both doGet and doPost, you might as well override the service method. So you can write a little bit less code. * /


Copy the code
  • Do we write HelloServlet that inherits HttpServlet directly, overriding the service() method in the HttpServlet class directly?

    • Yeah, except you don’t get the 405 error. You don’t enjoy the exclusive HTTP protocol.
  • Today we finally have a final Servlet class development step:

    • Step 1: Write a Servlet class that directly inherits HttpServlet
    • Step 2: rewrite the doGet method or the doPost method. It’s up to the javaweb programmer to decide which one to rewrite.
    • Step 3: Configure the Servlet class into the web.xml file.
    • Step 4: Prepare the front page (form form) and specify the request path in the form form.

Welcome page about a Web site

  • What is a Web site’s welcome page?

    • For a WebApp, we can set up its welcome page.
    • After setting up the welcome page, when you visit the WebApp or the Web site without specifying any “resource path”, it will default to your welcome page.
    • Our general access is as follows:
      • http://localhost:8080/servlet06/login.html is specified to access this way is the login. The HTML resources.
    • If we access by:
      • If we visit http://localhost:8080/servlet06 is this site, do not specify a specific resource path. Who does it access by default?
      • The default is the welcome page you set up.
  • How to set up the welcome page?

    • Step 1: I created a new file login. HTML in the Web directory of the IDEA tool

    • Step 2: The following configuration is performed in the web.xml file

      • <welcome-file-list>
                <welcome-file>login.html</welcome-file>
            </welcome-file-list>
        Copy the code
      • Note: When setting up the welcome page, the path does not need to start with a “/”. And by default, this path starts at the root of the WebApp.

    • Step 3: Start the server and enter the address in the browser address bar

      • http://localhost:8080/servlet07
  • If you create a new directory under the webApp root and give a file in the directory, how do you set up the welcome page?

    • Create a new page1 under webapp root

    • Create a new page2 directory under page1

    • Create a new page.html page in the page2 directory

    • This should be configured in the web.xml file

      • <welcome-file-list>
            <welcome-file>page1/page2/page.html</welcome-file>
        </welcome-file-list>
        Copy the code
      • Note: the path does not need to start with “/”, and the path is found from the root of webApp by default.

  • A WebApp can have multiple welcome pages

    • <welcome-file-list>
          <welcome-file>page1/page2/page.html</welcome-file>
          <welcome-file>login.html</welcome-file>
      </welcome-file-list>
      Copy the code
    • Note: The higher the priority, the higher the priority. If you can’t find it, keep looking.

  • Did you notice that when I set the file name to index.html, THERE was no need to configure the welcome page in the web.xml file? Why is that?

    • This is because the Kitty Tomcat server has been configured in advance.

    • There are actually two places to configure the welcome page:

      • One is in a web.xml file within webApp. (The configuration in this place is local configuration)

      • One is in the CATALINA_HOME/conf/web. XML file. (The configuration in this place is global.)

        • <welcome-file-list>
              <welcome-file>index.html</welcome-file>
              <welcome-file>index.htm</welcome-file>
              <welcome-file>index.jsp</welcome-file>
          </welcome-file-list>
          Copy the code
        • The global welcome page of the Tomcat server is index.html index.htm index.jsp. If you do not have a local welcome page for a web site, the Tomcat server will use index.html index.htm index.jsp as the welcome page for a web site.

      • Principle of attention: local priority. (Proximity principle)

  • Can the welcome page be a Servlet?

    • B: Sure.

    • You don’t want to think too much, the welcome page is a resource, since it is a resource, so it can be a static resource, can also be a dynamic resource.

    • Static resources: index.html welcome.html…..

    • Dynamic resources: Servlet class.

    • Steps:

      • Step 1: Write a Servlet

        • public class WelcomeServlet extends HttpServlet {
              @Override
              protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                  response.setContentType("text/html");
                  PrintWriter out = response.getWriter();
                  out.print("

          welcome to bjpowernode!

          "
          ); }}Copy the code
      • Step 2: Configure the servlet in the web.xml file

        •     <servlet>
                  <servlet-name>welcomeServlet</servlet-name>
                  <servlet-class>com.bjpowernode.javaweb.servlet.WelcomeServlet</servlet-class>
              </servlet>
              <servlet-mapping>
                  <servlet-name>welcomeServlet</servlet-name>
                  <url-pattern>/fdsa/fds/a/fds/af/ds/af/dsafdsafdsa</url-pattern>
              </servlet-mapping>
          Copy the code
      • Step 3: Configure the welcome page in the web.xml file

        •     <welcome-file-list>
                  <welcome-file>fdsa/fds/a/fds/af/ds/af/dsafdsafdsa</welcome-file>
              </welcome-file-list>
          Copy the code

About the WEB-INF directory

  • A new file is created in the WEB-INF directory: welcome.html
  • Open a browser visit: http://localhost:8080/servlet07/WEB-INF/welcome.html appeared a 404 error.
  • Note: Resources placed in the WEB-INF directory are protected. Cannot be accessed directly from the path in the browser. Static resources such as HTML, CSS, JS, and image must be kept out of the WEB-INF directory.

The HttpServletRequest interface is explained

  • It is an interface, the fully qualified name: Jakarta. Servlet. HTTP. It

  • The HttpServletRequest interface is a member of the Servlet specification.

  • The parent of the HttpServletRequest interface: ServletRequest

    • public interface HttpServletRequest extends ServletRequest {}
      Copy the code
  • Who wrote the implementation class for the HttpServletRequest interface? Who created the HttpServletRequest object?

    • By testing: org. Apache. Catalina. The RequestFacade implements the interface to it

      • public class RequestFacade implements HttpServletRequest {}
        Copy the code
    • The Tomcat server (WEB server, WEB container) implements the HttpServletRequest interface, or the Tomcat server implements the Servlet specification. For us JavaWeb programmers, we don’t really need to worry about that, we just need to program to the interface. What we care about is what methods are in the HttpServletRequest interface, and what can they do !!!!

  • What information is in the HttpServletRequest object? What kind of information does it contain?

    • The HttpServletRequest object is created by the Tomcat server. What information is encapsulated in this object? Encapsulates the HTTP request protocol.
    • In fact, when the user sends the request, it follows the HTTP protocol and sends the HTTP request protocol. The Tomcat server parses all the information and data in the HTTP protocol, and then encapsulates the information in the HttpServletRequest object. To us JavaWeb programmers.
    • Javaweb programmers program to the HttpServletRequest interface and call methods to retrieve the requested information.
  • The life cycle of the Request and Response objects?

    • Request object and Response object, one is the request object, one is the response object. These two objects are only valid for the current request.
    • Each request corresponds to one request.
    • Two requests correspond to two requests.
    • .
  • What are the common methods in the HttpServletRequest interface?

    • How do I get data submitted by front-end browser users?

      • Map<String,String[]> getParameterMapMap
        Enumeration<String> getParameterNames(a)Retrieve all key strings in the Map set []getParameterValues(String name)Gets the value String of the Map collection based on the keygetParameter(String name)Gets the first element of the one-dimensional array value. This method is most commonly used.// The above four methods are related to retrieving user-submitted data.
        Copy the code
      • Consider: If you submit data to the front-end form, how do you plan to store it, and what data structure do you plan to use to store it?

        • The data submitted by the front end is in the following format: username= abc&userPWd =111& AIhao = S&AIHAO = D&AIhao = TT

        • I will use the Map set to store:

          • Map<String,String> Key stores String value stores String, right? Not right. If the above data structure is used for storage, the value will be overwritten if the key is duplicated. key value --------------------- username abc userpwd111Aihao s aihao d aihao TT does not work because the map key cannot be repeated. Map < String, the String [] > key to store the String value stored String [] key value -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - the username {"abc"}
                userpwd			{"111"}
                aihao			{"s"."d"."tt"}
            Copy the code
        • Note: the front-end form submits data assuming a “number” such as 120, which is actually submitted as a string of “120”, so the server must get a string of “120”, not a number. (The front end always submits strings, and the back end always retrieves strings.)

    • Develop a Webapp by hand. Test the related methods in the HttpServletRequest interface.

      • We first tested four common methods, four methods for getting request parameters.

        • 	Map<String,String[]> parameterMap = request.getParameterMap();
          	Enumeration<String> names = request.getParameterNames();
          	String[] values = request.getParameterValues("name");
          	String value = request.getParameter("name");
          Copy the code
      • The Request object is actually called a “request domain” object.

        • What is an application domain object?

          • ServletContext (Servlet context object.)

          • When would you consider binding data to the ServletContext application domain?

            • First: data shared by all users.
            • Second: the amount of data shared is small.
            • Third: this shared data is rarely modified.
            • When the above three conditions are met, using this application domain object can greatly improve the efficiency of our program execution.
            • In fact, binding data to the application domain is equivalent to storing data in the Cache. When users access data, they directly fetch data from the Cache, reducing I/O operations and greatly improving system performance. Therefore, caching technology is an important means to improve system performance.
          • What caching techniques have you seen?

            • String constant pool
            • Integer constant pool [-128 to 127], but any Integer object in this range does not create a new object, directly from the Integer constant pool. Greatly improve system performance.
            • Database connection pool (N connection objects created in advance, put the connection object into the collection, when using the connection object, directly from the cache. The creation of a connection object is omitted. Increased efficiency.)
            • Thread pooling (The Tomcat server supports multithreading. A thread pool is a collection of N thread objects that are created in advance, stored in a collection, and then, when the user requests it, fetched the thread object directly from the pool and used it. Improve system performance)
            • Later you will learn more about caching techniques such as Redis and mongoDB…..
          • ServletContext has three methods for manipulating domains:

            • void setAttribute(String name, Object obj); // Bind data to the domain.
              Object getAttribute(String name); // Get data from the domain by name.
              void removeAttribute(String name); // Remove the bound data from the domain
              
              // The above operation is similar to the operation of Map collection.
              Map<String, Object> map;
              map.put("name", obj); // Put keys and values into the map collection
              Object obj = map.get("name"); // Get the value from the key of the map collection
              map.remove("name"); // Delete the key and value pairs from the Map set.
              Copy the code
        • Request Domain object

          • The Request domain object is much smaller in scope than the Application domain object. The life cycle is much shorter. Request fields are only valid for a single request.

          • One request object, request, corresponds to one request domain object. At the end of a request, the request field is destroyed.

          • The request domain object also has these three methods:

            • void setAttribute(String name, Object obj); // Bind data to the domain.
              Object getAttribute(String name); // Get data from the domain by name.
              void removeAttribute(String name); // Remove the bound data from the domain
              Copy the code
          • How to choose request domain and application domain?

            • Try to use small domain objects because they consume fewer resources.
        • jump

          • Forward (a request)

            • // Step 1: Get the request forwarder object
              RequestDispatcher dispatcher = request.getRequestDispatcher("/b");
              // Step 2: Call the forwarder's forward method to complete the forward/forward
              dispatcher.forward(request,response);
              
              // Step 1 and step 2 codes can be combined.
              request.getRequestDispatcher("/b").forward(request,response);
              
              Copy the code
        • How do two servlets share data?

          • Putting data into the ServletContext application domain is certainly possible, but the application domain is too large and takes up too many resources. Not recommended.
          • Data can be placed in the Request field and then forwarded by AServlet to BServlet, ensuring that AServlet and BServlet are in the same request. This allows two servlets, or multiple servlets, to share the same data.
        • Does the next resource to forward have to be a Servlet?

          • Not necessarily, as long as the legitimate resources in the Tomcat server, can be forwarded. For example: HTML…
          • Note: When forwarding, note that the path should start with “/” without the project name.
        • There are two very confusing methods in the Request object:

          • 
            // uri? username=zhangsan&userpwd=123&sex=1
            String username = request.getParameter("username");
            
            Request.setattribute ("name", new Object())
            Object obj = request.getAttribute("name");
            
            // What is the difference between the two methods?
            // The first method is to get the data submitted by the user on the browser.
            // The second method is to get the data bound in the request field.
            Copy the code
        • Other common methods of the HttpServletRequest interface:

          • // Obtain the CLIENT IP address
            String remoteAddr = request.getRemoteAddr();
            
            // GET requests submit data on the request line.
            // THE POST request submits data in the request body.
            // Set the character set for the request body. (Apparently this method handles POST request garbled characters. This approach does not solve the problem of garbled GET requests.
            // After Tomcat10, the default character set in the request body is UTF-8. There is no need to set the character set and garbled characters will not occur.
            // Before Tomcat9 (including 9), if the front-end request body is submitted in Chinese and the back-end request body is retrieved, how to solve the garbled code? Execute the following code.
            request.setCharacterEncoding("UTF-8");
            
            // Before Tomcat9 (including 9), the response Chinese is also garbled, how to solve this response garbled?
            response.setContentType("text/html; charset=UTF-8");
            // After Tomcat10, including 10, there is no garble problem when responding to Chinese. The above code does not need to set utF-8.
            
            // Pay attention to one detail
            // In Tomcat10 and later versions, Chinese characters will no longer appear garbled. (It also reflects the rising status of The Chinese language.)
            
            // Get requests are garbled.
            When a GET request is sent, the data is submitted on the request line, not in the request body.
            // Get requests are garbled
            // Solution: Modify the CATALINA_HOME/conf/server. XML configuration file
            <Connector URIEncoding="UTF-8" />
            // Note: since Tomcat8, URIEncoding defaults to UTF-8, so GET requests are not garbled.
                
            // Get the root path of the application
            String contextPath = request.getContextPath();
            
            // Get the request mode
            String method = request.getMethod();
            
            // Get the request URI
            String uri = request.getRequestURI();  // /aaa/testRequest
            
            // Get the servlet path
            String servletPath = request.getServletPath(); // /testRequest
            
            Copy the code

Do a single table CRUD operation using a pure Servlet