I. Introduction to Servlets

1. Three major components of JavaWeb:

① Servlet program ② Filter ③ Listener

2. What is a Servlet?

Servlets are one of the Java EE specifications.

It is running on the server of a Java small program, can receive the client sent over the request, and respond to the data to the client.

(1) : Tomcat receives and parses the HTTP request text, and then encapsulates it into an HttpServletRequest type Request object. All HTTP header data reads can be queried by calling the corresponding method of the Request object.

(2) : Tomcat also requires the response information to be encapsulated as a response object of type HttpServletResponse. By setting the response property, you can control the output to the browser, and then hand the response to Tomcat. Tomcat sends it as response text to the browser

The Java Servlet API is an interface between the Servlet container (Tomcat) and servlets. It defines serlvet methods and object classes that the Servlet container passes to servlets. The most important of these are ServletRequest and ServletResponse. So when we write a servlet, we need to implement the servlet interface and operate according to its specifications.

3. Manually implement servlets

① Write a class to implement the Servlet interface

Create a MyServlet that inherits HttpServlet, overrides the doGet and doPost methods to see if the request is get or POST, and then handles the request differently

public class MyServlet extends HttpServlet {}Copy the code

Override doGet and doPost methods

② Implement the service method to process requests and respond to data. (Services are used to process requests and responses)

③ Go to web. XML to configure the access address of the servlet program

What it does: Let the browser know which servlet the request goes to, that is, let Tomcat find the corresponding servlet to use the wrapped request.


(1) the first browser via http://localhost:8080/test01/MyServlet (a URL address: Servlet backend address) to trigger access to the routing configuration in the Servlet, find the URL-pattern in the servlet-mapping node in web.xml;

② After matching the URL-pattern, the name of the second step servlet MyServlet will be found.

③ If you know the name, you can find the servlet node by servlet-name. If you find the node with the same name, you can know the location of the servlet.

④ Finally get a back-end class, to find the corresponding processing method for processing.

Servlet life cycle

Three important methods of servlet backend classes:

A servlet object is initialized when the server starts (load-on-startup=1 in web.xml, default is 0) or when the servlet is requested for the first time, that is, init(ServletConfig conf) is executed.

The servlet object handles all client requests, executed in the Service (ServletRequest req, ServletResponse Res) method

Finally, the servlet object is destroyed when the server is shut down, using the destroy() method.