Remote CGI
Web dynamic content technology, the earliest use of CGI (Common Gateway Interface) technology, according to the user input request to dynamically transfer HTML data. CGI is not a development language, but simply a protocol for implementing Web servers using programs written for it. Can be used to achieve e-commerce sites, search engine processing and online registration functions. When a user submits input data in a Web page, the Web browser sends the data to the Web server. On the server, the CGI program formats the input data, sends this information to the database or other programs running on the server, and returns the results to the Web server. Finally, the Web server sends the results to the Web browser, which are sometimes displayed using a new Web page or within the current Web page.
Writing custom CGI scripts requires considerable programming skill. Most CGI scripts are written in Perl,Java,C, and C++ languages. Server scripts written in JavaScript are rarely run on servers. Includes the required background programs (such as databases) that provide results or messages from users. Even with server-based web design tools, writing CGI programs requires some experience from the programmer.
One of the big drawbacks of CGI is that it can slow down the Web server because each request for dynamic content requires a new CGI program to be started, which adds to the burden on the Web server.
scripting
Because CGI programs and HTML documents need to be written and run separately, it is not easy to blend the two together, so it is difficult to maintain and write CGI programs. To solve this problem, some vendors have introduced scripting languages to enhance web development capabilities.
Scripting language is a text-based programming language that can be embedded in HTML documents. There are two types of scripting languages, client side and server side, running in Web browsers and Web servers respectively.
Client scripting languages mainly include JavaScript, Jscript (Microsoft’s version of JavaScript) and VBscript. When the Web browser needs to browse the Web page written in the client scripting language, the Web server sends the client script together with the Web page to the Web browser. The Web browser displays the display effect of HTML and the running effect of the client script at the same time. The client script can reduce the processing burden of the Web server. Improves Web page response speed.
Server-side scripting languages include ASP, JSP, PHP and LiveWire. When a Web browser needs to browse a Web page written in a server-side scripting language, the Web server runs the server-side scripts in the Web page and sends the new Web page generated by the running results of the scripting language and the HTML part of the Web page to the Web browser, which displays the new Web page generated. Server-side scripts reduce the running differences between different Web browsers and improve the usability of Web pages.
During this time, Java’s Servlet model was born.
2 Servlet
A Java technology-based Web component for generating dynamic content, managed by a container. Like other Java technology components, servlets are composed of platform-independent Java classes that are loaded and executed by a Java Web server.
The runtime environment is typically provided by a Servlet container. A Servlet container, sometimes called a Servlet engine, is part of a Web server or application server. Provide the ability for Web clients to interact with Servlets through request and response dialogues. The container manages Servlets instances and their life cycles.
Major version
Core components
Core Component API | instructions | The initial version | Spring Framework stands for implementation |
---|---|---|---|
javax. servlet .Servlet | Dynamic content Component | 1.0 | DispatcherServlet |
javax. servlet .Filter | The Servlet filter | 2.3 | CharacterEncodingFilter |
javax. servlet .ServletContext | Servlet application Context | ||
javax. servlet .AsyncContext | Asynchronous context | 3.0 | There is no |
javax. servlet .ServletContextistener | ServletContext Lifecycle listener | 2.3 | ContextLoaderListener |
javax . servlet . ServletRequestlistener | ServletRequest lifecycle listener | 2.3 | RequestContextListener |
javax. servlet .http.HttpSessionListener | Lifecycle listeners | 2.3 | HttpSessionMutexListener |
javax. servlet .Asynclistener | Asynchronous context listeners | 3.0 | StandardServletAsyncWebRequest |
javax. servlet .ServletContainerInitializer | Servlet container initializer | 3.0 | SpringServletContainerInitializer |
The browser sends an HTTP request to the server. After receiving the request, the HTTP server invokes the server program to process the request.
How does the HTTP server know which processor method to call?
The simplest is to write A bunch of if/else in the HTTP server code: call m1 of class X if A requests it, and m2 of class O if B requests it. The death of this design is that the HTTP server code is coupled to the business logic, and if you add a business method, you have to change the HTTP server code. Interface oriented programming is the silver bullet to solve the coupling problem. We can define an interface that all business classes implement. Yes, it is a Servlet interface, and the business class that implements the Servlet interface is called a Servlet.
Having solved the coupling problem between the business logic and the HTTP server, there is another problem: how does the HTTP server know about a particular request:
- Which Servlet handles the request?
- Who is responsible for instantiating the Servlet?
Clearly the HTTP server is not in a position to be responsible for this, otherwise it would be coupled to the business logic.
Thus, the Servlet container was born.
3 the Servlet container
Used to load and manage business classes.
Instead of interacting directly with the business class, the HTTP server first passes the request to the Servlet container, which internally forwards the request to the specific Servlet. If the Servlet is not already created, load and instantiate it, and then call the interface methods of the Servlet.
So the Servlet interface is really the interface between the Servlet container and the concrete business class:Left: THE HTTP server invokes concrete business classes directly, but tightly coupled. Right: The HTTP server does not call the business class directly, but hands off the request to the container, which calls the business class through the Servlet interface. Therefore, the Servlet interface and Servlet container realize the decoupling of HTTP server and business class.
The whole set of specifications for Servlet interfaces and Servlet containers is called the Servlet specification. Tomcat implements the Servlet container and HTTP server functions according to the Servlet specification. If you implement a new business, you simply implement a Servlet, register it with Tomcat (the Servlet container), and Tomcat does the rest.
4 the Servlet interface
The Servlet interface defines the following five methods:
The concrete business class implements the processing logic in the Service method, and these two classes encapsulate the communication protocol:
- ServletRequest
Encapsulate request information
- ServletResponse
Encapsulate response information
HTTP requests and responses correspond
- HttpServletRequest
Gets all request-related information, including request path, cookies, HTTP headers, request parameters, and so on. You can also create and obtain sessions
- HttpServletResponse
Encapsulating HTTP responses
Lifecycle related methods:
- init
The Servlet container calls the Servlet class when it is loaded, possibly initializing some resources in the init method. The DispatcherServlet in Spring MVC, for example, creates its own Spring container in the init method.
- destroy
Called during uninstallation, possibly freeing these resources in the destroy method
ServletConfig
The ServletConfig encapsulates the initialization parameters of the Servlet. You can configure parameters for the Servlet in web.xml and get them in the application using getServletConfig.
Abstract classes are used to implement interfaces and encapsulate common logic, so the Servlet specification provides GenericServlet abstract classes that can be extended to implement servlets. Although the Servlet specification does not care what the communication protocol is, most servlets are handled in an HTTP environment, so the Servet specification also provides HTTPServlets to inherit GenericServlets and add HTTP features. Thus we implement our own Servlet by inheriting the HttpServlet class, overriding only two methods: doGet and doPost.
5 the Servlet container
The working process
When a client requests a resource
- The HTTP server encapsulates the customer’s request information with a ServletRequest object
- The Servlet container’s service method is then called
- The Servlet container takes the request and finds the corresponding Servlet based on the mapping between the requested URL and the Servlet
- If the Servlet has not already been loaded, it is created with reflection
- Call the init method of the Servlet to complete initialization
- Call the Servlet’s Service method to handle the request
- The ServletResponse object is returned to the HTTP server, which sends the response to the client
The Web application
The Servlet container instantiates and calls servlets. How do servlets register with the Servlet container?
According to the Servlet specification, Web applications have a certain directory structure that is placed
- The Servlet class file
- The configuration file
- Static resource
The Servlet container finds and loads the Servlet by reading the configuration file. Rough directory structure for Web applications:
| - MyWebApp | - WEB - INF/WEB. The XML configuration file, Used to configure the Servlet etc. | - WEB - INF/lib / - contains various JAR package | required WEB application - the WEB - INF/classes/deposit - your application class, such as a Servlet class | - meta-inf/directory - storage engineering of some informationCopy the code
6 ServletContext
Defines a set of methods that servlets use to communicate with their servlet containers. Such as getting the MIME type of a file, scheduling a request, or writing to a log file. Each JVM’s Web application has a context. Web applications are installed under a specific subset of the server URL namespace, such as /catalog, and may pass. War file is a collection of installed services and content. If marked in the deployment descriptor
In distributed systems, each machine node has a context instance. In this case, the context cannot be used as a place to share global information (because the information will not be truly global). External resources such as databases should be used instead. The ServletContext object is contained in the ServletConfig object and is provided by the Web server when the server is initialized.
The Servlet specification defines the ServletContext interface for a Web application. For example, a SpringBoot application would have only one ServletContext. Not to be confused with Spring’s applicationContext, because there can be multiple Spring ApplicationContexts in an application.
After the Web application is deployed, the Servlet container loads the Web application at startup and creates a global context ServletContext object for each Web application to host the subsequent Spring container.
Consider the ServletContext as a global object. A Web application may have multiple servlets that share data with the global ServletContext:
- Initialization parameters of the Web application
- File resources in the Web application directory
The ServletContext holds all Servlet instances, so it can also forward Servlet requests.
Tomcat&Jetty triggers a container initialization event during startup. Spring’s ContextLoaderListener listens for this event and its contextInitialized method is called. In this method, Spring initializes the global Spring root container, which is Spring’s IoC container. After the IoC container is initialized, Spring stores it toServletContext, so that you can obtain it later.The ServletContext is used to share data. For example, SpringMVC needs to take the global Spring container from the ServletContext and set it up as its parent.
Tomcat&Jetty also scans servlets during startup. A Web application can have multiple servlets. For example, the DispatcherServlet in SpringMVC is actually a standard front-end controller. To forward, match, and process each Servlet request.
Servlets typically load lazily. When the first request arrives, Tomcat&Jetty finds that the DispatcherServlet has not yet been instantiated and calls the init method of DispatcherServlet. When the DispatcherServlet is initialized, it creates its own container, called the SpringMVC container, to hold Spring MVC-related beans. SpringMVC also uses the ServletContext to get the Spring root container and set it as the parent of the SpringMVC container. Note that the SpringMVC container can access the beans in the parent container, but the parent container cannot access the beans in the child container. That is, the Spring root container cannot access beans in the SpringMVC container. In plain English, you can access a Service object in a Controller, but you can’t access a Controller object in a Service.
Initialization work
Tomcat/Jetty starts and initializes each WebApp in turn: For each WebApp, there is a WebApp ClassLoader and a ServletContext. When the ServletContext is started, it scans the web. XML configuration file to find the Filter, Listener, and Servlet configuration
If the Listener is equipped with Spring ContextLoaderListener 3.1, ContextLoaderListener will receive various webApp status information. 3.3. When the ServletContext is initialized, the ContextLoaderListener also initializes the Spring IOC container to manage spring-related beans. ContextLoaderListener stores the Spring IOC container in the ServletContext
4. If the Servlet is equipped with SpringMVC’s DispatcherServlet 4.1, DispatcherServlet initialization (one request arrives). 4.2, where DispatcherServlet initializes its own SpringMVC container to manage SpringMVC related beans. 4.3. The SpringMVC container can get the Spring container through ServletContext and set it as its root container. The child container can access the parent container, so the Service object can be accessed in the Controller, but the Controller object cannot be accessed in the Service. 4.2 after initialization, DispatcherServlet starts to process the request mapping relationship in MVC.
Servlets default to singletons, and Spring beans default to singletons. How does Spring MVC handle concurrent requests? Member variables in dispatcherServlets are initialized and will not be changed, so they are thread-safe. Guaranteed by Web containers such as Tomcat, which uses synchronized when calling the init method of servlets.
- Load and initialize an instance of the servlet if there is not at least one initialized instance already. For example, this can be used to load servlets in the Deployment Descriptor marked to load at server startup.
Implementation description: Class name withorg.apache.catalina.
The leading Servlet org.apache.catalina. (the so-called Servlet container) is loaded by the same class loader that loaded this class, not by the current Web application’s class loader. This gives this class access to Catalina internal structures that is blocked for classes loaded for Web applications
Extension mechanism
With the introduction of the Servlet specification, you don’t need to worry about Socket network traffic, HTTP, or how your business classes are instantiated and called, because that’s all standardized by the Servlet specification, you just need to worry about implementing the business logic.
Having a specification may seem convenient, but it won’t work if the specification doesn’t fit your personality needs, so design a specification or middleware with extensibility in mind. The Servlet specification provides two extension mechanisms: Filter and Listener.
Filter
Filters, an interface that allows you to do some unified customization of requests and responses. A Filter is process-based, it is part of a process, and it is based on process behavior. Such as:
- Restrict access based on the frequency of requests
- Modify the response content based on the region
Filters are one of the important standards for servlets:
- Unified processing of requests and responses
- Access logging
- Request permission review
. All play an important role
The working principle of
After the Web application is deployed, the Servlet container instantiates the Filter and links the Filter to a FilterChain. When the request comes in, the first Filter is retrieved and the doFilter method is called, which is responsible for calling the next Filter in the FilterChain.
Listener
The Listener is based on the state, any behavior changes to the same state, trigger the event is consistent. When the Web application runs in the Servlet container, various events occur constantly inside the Servlet container, such as the start and stop of the Web application and the arrival of user requests. The Servlet container provides some default listeners to listen for these events, and when the event occurs, the Servlet container is responsible for calling the listener’s methods. Of course, you can define your own listeners to listen for events you are interested in, configuring them in web.xml. Spring, for example, implements its own listener to listen for ServletContext startup events, with the goal of creating and initializing the global Spring container when the Servlet container is started.
X FAQ
Why does the service method take both request and Response as input parameters instead of just request and response as return parameters? Convenient responsibility chain mode layer by layer transfer.
Why is there no web.xml in the SpringBoot project? SpringBoot is an embedded way to start Tomcat. To SpringBoot, Tomcat is just a JAR package. SpringBoot adds servlets directly to the Servlet container through the @webServlet annotation or API in the Servlet3.0 specification, without the need for web.xml.
Indistinguishable XXX container
The Servlet container
Used to manage the Servlet life cycle.
For SpringMVC container
Manage the SpringMVC Bean lifecycle.
The Spring container
Used to manage the Spring Bean lifecycle. Contains many sub-containers, among which the SpringMVC container is commonly used, DispatcherServlet is the servlet interface in the SpringMVC container, but also the core class of SpringMVC container.
The Spring container is mainly used for some components that need to be shared by the entire Web application, such as DAO, ConnectionFactory of the database, etc. The SpringMVC container is mainly used for some components related to the Servlet, such as Controller, ViewResovler, etc. At this point, the relationships inside the Spring container are clear.
Spring and SpringMVC each have their own IOC container or context. Why are they divided into two containers? Isolated managed beans, each with its own responsibilities, are clearly defined. The SpringMVC container directly manages the beans associated with DispatcherServlet (Controller, ViewResolver, etc.) and is created in the init method of DispacherServlet. The Spring container manages other beans such as Services and DAOs.
And the SpringMVC container is a child of the Spring container, so what does parent-child relationship mean? When you get a Bean from the child container, the child container looks for the Bean in its own managed Bean, and if it can’t find it, it looks for the Bean in the parent container. But the parent container cannot go to the child container to find a Bean.
This is similar to the JVM’s classloader design, where different classloaders are used to isolate each other, but the loading order is reversed. The child loader always delegates to the parent loader to load a class before loading it itself.
And parent-child relationships allow the SpringMVC container to take beans from the parent Spring container, because the Spring container manages common beans. Of course you can manage it with the same container, which is what SpringBoot does.
Spring and SpringMVC explicitly specify the beans they manage through configuration files.
What does the Servlet container have to do with the Spring container? Some people say that the Spring container is a child of the Servlet container, but is the servlet container a tomcat implementation or a Jetty implementation? Therefore, there is no direct kinship between the Spring container and the Servlet container. It can be said that the Spring container relies on the servlet container, and the implementation of the Spring container follows the servlet specification.
The Spring container is just a property of the ServletContext, which is constructed by the ServletContextListener mechanism when the Web container starts. There is only one Spring context in SpringBoot:
org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext
Copy the code
After the servlet container is initialized successfully, the spring container is listened by spring, the spring container is created and put into the servlet container, the access arrives, the SpringMVC container is created when the Dispatcher servlet is initialized, and the Spring container is retrieved through the servletContext. As its parent, the Spring MVC container defines controller related beans, and Spring defines business logic related beans.
reference
- Blog.csdn.net/zhanglf02/a…
- Docs.oracle.com/cd/E19146-0…
- Matthung0807.blogspot.com/2020/09/tom…
- Github.com/heroku/devc…
- Biang. IO/blog/mixed /…