Case Approach

This case is a transfer scenario. Here we directly use the interface approach without implementing a specific page, simulating through interface calls. Eventually, we will implement various features without using Spring.

Add Dependencies

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.32</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.21</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.6</version>
    </dependency>
    <dependency>
        <groupId>dom4j</groupId>
        <artifactId>dom4j</artifactId>
        <version>1.6.1</version>
    </dependency>
    <dependency>
        <groupId>jaxen</groupId>
        <artifactId>jaxen</artifactId>
        <version>1.1.6</version>
    </dependency>
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>2.1_2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-core</artifactId>
        <version>9.0.39</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <version>9.0.39</version>
    </dependency>
</dependencies>

What is a Servlet?

A Servlet is part of Java EE technology used to create dynamic Web applications. It is a small Java program running on the server side to handle client requests and generate dynamic responses. The core purpose of a Servlet is to extend server functionality, especially for handling HTTP-based requests.

Core Servlet Concepts

  • Servlet Container: Servlets are managed by a Servlet container (such as Tomcat, Jetty, etc.)
  • Request-Response Model: Servlets use the HTTP request and response model to handle client requests
  • Lifecycle: Loading and instantiation → Initialization (init()) → Service (service()) → Destruction (destroy())

Servlet Characteristics

  • Platform independence: Based on Java technology, can run on any Web server supporting Java
  • Efficiency: Uses threads to handle requests, avoiding the overhead of creating a new process for each request
  • Security: Java provides built-in security mechanisms
  • Convenience: Develop dynamic Web applications through standard APIs and Java’s powerful functionality

How Servlets Work

  1. Client request: Browser sends HTTP request to the Web server
  2. Container dispatch: Web server passes the request to the Servlet container
  3. Request processing: Servlet container calls the service() method, invoking doGet() or doPost() based on request type
  4. Return response: Container sends the response back to the client

Servlet Code

package wzk;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.io.IOException;

@WebServlet(name="wzkServlet", urlPatterns = "/wzkServlet")
public class WzkServlet extends HttpServlet {

    @Override
    protected void doGet(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp) throws javax.servlet.ServletException, IOException {
        System.out.println("doGet!");
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print("hello!");
    }

}

Startup Class

package wzk;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;

import java.io.File;

public class WzkStart {

    public static void main(String[] args) throws LifecycleException {
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(Integer.getInteger("port", 8999));
        tomcat.getConnector();
        Context context = tomcat.addWebapp("", new File("src/main/webapp").getAbsolutePath());
        WebResourceRoot resources = new StandardRoot(context);
        resources.addPreResources(
                new DirResourceSet(resources, "/WEB-INF/classes",
                        new File("target/classes").getAbsolutePath(), "/"));
        context.setResources(resources);

        tomcat.start();
        tomcat.getServer().await();
    }

}

Run the Code

Run WzkStart, console output:

Nov 18, 2024 4:12:41 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Nov 18, 2024 4:12:41 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8999"]

Access the Project

Access address: http://localhost:8999/wzkServlet

Return result: hello!

Database

Create New Table

CREATE TABLE `wzk_account` (
  `card` varchar(255) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  `money` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;

Insert Data

INSERT INTO wzk_account VALUES('1', 'wzk', 500);
INSERT INTO wzk_account VALUES('2', 'icu', 500);