Servlets are short for Server applets.

Servlets are a set of Java technical standards that specify how to use Java to develop dynamic web sites.

In other words, Java can be used to develop web sites behind the scenes, but you need to define a set of specifications in advance and write the base class libraries, which is what servlets do.

Java servlets can use all the Java apis and do everything Java can do.

To share this set of Servlet introduction videos, the overall framework of Servlet technology is explained, and accompanied by an example demonstration, Java foundation is required.

Free to watch online:

www.bilibili.com/video/BV1y5…

Information download:

www.bjpowernode.com/javavideo/1…

Servlets were a replacement for the older CGI technology, and it was still cumbersome to develop directly with Servle, so Java later upgraded servlets with JSP technology. JSP is just a shell on a Servlet, JSP is still a Servlet when compiled.

What is a Servlet?

Java servlets are programs that run on a Web server or application server as an intermediate layer between requests from a Web browser or other HTTP client and a database or application on an HTTP server.

With servlets, you can collect user input from web forms, render records from databases or other sources, and create web pages on the fly.

Java servlets often have similar effects to programs implemented using Common Gateway Interface (CGI). But servlets have several advantages over CGI:

• Significantly better performance.

• Servlets execute within the address space of the Web server. This eliminates the need to create a separate process to handle each client request.

• Servlets are platform independent because they are written in Java.

• The Java security manager on the server executes a number of restrictions to protect resources on the server machine. Therefore, servlets are trusted.

• All the functionality of the Java class library is available to servlets. It can interact with applets, databases, or other software using Sockets and RMI mechanisms.

The Servlet architecture

The following figure shows the location of servlets in a Web application.

Servlet implementation process

JavaSoft Java Web Server was the first to support Servlet technology. Since then, several other Java-based Web Servers have begun to support the standard Servlet API. The main function of servlets is to interactively browse and modify data to generate dynamic Web content. The process is as follows:

• The client sends requests to the server.

• The server sends the request information to the Servlet;

• The Servlet generates the response content and passes it to the server. Response content is generated dynamically, usually depending on the client’s request;

• The server returns the response to the client.

• Servlets look like normal Java programs. Servlets import specific packages that belong to the Java Servlet API. Because they are object bytecodes that can be loaded dynamically from the network, servlets can be said to be to the Server what applets are to the Client, but because servlets run in the Server, they do not need a graphical user interface. In this sense, servlets are also called FacelessObject.

• A Servlet is a class in the Java programming language that is used to extend the performance of a server that hosts applications that can be accessed through the request-response programming model. Although servlets can respond to any type of request, they are typically used only to extend Web server applications.

The Servlet named

Servlet naming can be seen in Sun naming characteristics, such as Applet for small applications; Scriptlet = Script + Applet Similarly, Servlet = Service + Applet represents a small Service program.

Life cycle editing

The client requests the Servlet;

Load the Servlet class into memory.

Instantiate and call the init() method to initialize the Servlet;

Service () (calls doGet() or doPost(), depending on the request method, as well as doHead(), doPut(), doTrace(), doDelete(), doOptions());

Destroy ().

Load and instantiate servlets. This operation is usually performed dynamically. However, servers typically provide an administrative option to force loading and initialization of specific servlets at Server startup.

Server creates an instance of a Servlet

The first client request reaches the Server

The Server calls the init() method of the Servlet (which can be configured when creating Servlet instances for the Server. The value is an integer under the tag in web.xml. The smaller the value, the higher the startup priority of the Servlet.)

A client request reaches the Server

The Server creates a request object that handles the client request

The Server creates a response object that responds to a client request

Server activates the Servlet’s Service () method, passing request and response objects as parameters

The service() method obtains information about the request object, processes the request, accesses other resources, and obtains the required information

The service() method uses the methods of the response object to pass the response back to the Server and eventually to the client. The service() method may activate other methods to handle requests, such as doGet() or doPost(), or a new method developed by the programmer himself.

For more client requests, Server creates new request and response objects, still activating the Servlet’s service() method, passing these two objects as parameters to it. Repeat the loop without calling the init() method again. Typically servlets are initialized once (only one object), and when the Server no longer needs the Servlet (typically when the Server is shut down), the Server calls the destroy() method of the Servlet.

Servlet working mode

The client sends a request to the server;

The server starts and invokes the Servlet, which generates the response content based on the client request and passes it to the server;

The server returns the response to the client.

contrast

Comparison with applets

Similarities:

• They are not standalone applications and do not have main() methods. • They are not called by the user or programmer, but by another application (container). • They all have a lifetime and contain init() and destroy() methods.

Differences:

• Applets have a nice graphical interface (AWT) that runs on the client side with the browser. • Servlets have no graphical interface and run on the server side.

Compared with CGI

Compared to traditional CGI and many other CGI-like technologies, Java servlets are more efficient, easier to use, more powerful, more portable, and less costly. In the future, servlets may completely replace CGI.

In traditional CGI, a new process is started for each request, and if the CGI program itself is short in execution time, the cost of starting the process is likely to exceed the actual execution time. In servlets, each request is handled by a lightweight Java thread (rather than a heavyweight operating system process).

In traditional CGI, if there are N concurrent requests for the same CGI program, the code for that CGI program is loaded in memory N times. With servlets, N threads process requests and only one servlet-class code is required. Servlets also have more options than CGI for performance optimization.

Convenient,

Servlets provide a number of utility routines, such as automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking session state, and so on.

• Powerful

In servlets, many tasks can be easily done that would be difficult to do with traditional CGI programs. For example, servlets can interact directly with Web servers, whereas regular CGI programs cannot. Servlets also have the ability to share data between programs, making features like database connection pooling easy to implement.

• Good portability

Servlets are written in Java, and the Servlet API has a complete standard. Therefore, servlets written for IPlanet Enterprise Server can be ported to Apache, Microsoft Is, or WebStar without any substantial changes. Almost all major servers support servlets either directly or through plug-ins.

• Save investment

Not only are there many inexpensive or even free Web servers available for individuals or small Web sites, but it’s often free (or minimal investment) to add this functionality to an existing server if it doesn’t support servlets.

Compared with the JSP

JSP and Servlet difference in the application of what is reflected, many people do not understand. To put it simply, SUN first developed the Servlet, which has relatively powerful functions and advanced system design. However, it still uses the old CGI method to output HTML statements, which is output sentence by sentence. Therefore, it is very inconvenient to write and modify HTML.

Java Server Pages(JSP) is a technology that implements a mixture of normal static AND dynamic HTML encoding, and JSP does not add any functionality that is inherently impossible to implement with servlets. However, it is much easier to write static HTML in JSPS without having to print out each line of HTML in println sentences. More importantly, with the separation of content and appearance, tasks of different nature in page production can be easily separated: for example, HTML design by page designers, while leaving room for Servlet programmers to insert dynamic content.

Later SUN launched similar to ASP Mosaic type JSP, JSP TAG Mosaic to HTML statements, so, greatly simplified and convenient web design and modification. New network languages such as ASP, PHP, JSP are Mosaic languages. This is the operational level of the difference between JSP and Servlet.

Look at the difference between JSP and Servlet from the perspective of three-layer network structure, a network project is divided into at least three layers: Data layer, Business layer, Presentation layer. It could be more complicated. Servlets are great for writing the Business Layer, but inconvenient for writing the Presentation Layer. JSP is mainly designed to facilitate writing the Presentation layer. You can also write business Layer. Friends who are used to writing ASP, PHP and CGI often mix the Presentation layer with the business layer unconsciously.

According to SUN’s own recommendation, JSPS should only place things related to the Presentation layer, that is, only the parts that output the HTML page. All data computation, data analysis, and database join processing are business Layer and should be in Java BEANS. Java BEANS are invoked through JSP to achieve integration of the two layers.

Microsoft recently launched DNA technology, is ASP+COM/DCOM technology. Exactly like J SP+BEANS, all presentation layer is done by ASP and all business layer is done by COM/DCOM. Integration is implemented through invocation.

Using these component technologies simply because ASP/JSP language is very inefficient implementation, if there is a large number of users click, pure SCRIPT language soon reached his functional ceiling, and component technology can greatly improve the functional ceiling, speed up the execution.

On the other hand, a pure SCRIPT language mixes the Presentation layer with the Business layer, making it difficult to change, and the code cannot be reused. If you want to change a place, it often involves more than a dozen pages of code, and with component technology you can just reshuffle it.

To sum up, servlets are an early, imperfect product that writes well at the Business Layer and stinks at the Presentation Layer and mixes the two layers.

So, JSP+ beans, JSP to write presentation layer, beans to write business layer. SUN’s own intention is to replace servlets with JSPS in the future. This is the difference between JSPS and servlets in terms of technology updates.

However, this is not to say that learning Servlet is useless, in fact, you should start with Servlet, then JSP, then JSP+BEAN.

Emphasize is: learned JSP, will not use Java beans and integration, equal to did not learn. Put more effort into JSP+ beans.

We can see that when ASP+COM and JSP+BEAN adopt component technology, all components are compiled first, and reside in memory, and then execute quickly. As a result, the oft-touted speed advantage of servlets/JSPS compiled in memory and then executed is lost.

On the contrary, ASP+COM+IIS+NT closely integrated, should have a greater speed advantage. Moreover, ASP+COM+IIS+NT development efficiency is very high, although there are many bugs.

So why JSP+ Beans? Because Java really has a future. When operating systems become dominant, application software developers must find a common language to develop, and Java’s time is up.

Briefly analyzed the difference between JSP and Servlet and the development of Java Web development. As machines get faster and faster, Java’s speed disadvantage can be quickly overcome.

specification

1. Simplify development

2. Easy to deploy

3. Support Web2.0 principles

To simplify the development process, Servlet 3.0 introduced annotations, making the Web deployment descriptor Web.xml no longer a necessary choice.

Pluggability Pluggability

When using any third party framework, such as Struts, JSF, or Spring, we need to add the corresponding Servlet entry to web.xml. This makes web descriptors cumbersome and difficult to maintain. The new pluggable features of Servlet3.0 make web applications modular and easy to maintain. Pluggability through Web Fragments relieves developers of the need to configure many Servlet entries in web.xml.

Asynchronous Processing Asynchronous Processing

Another notable change is Servlet 3.0’s support for asynchronous processing, which is useful for AJAX applications. When a Servlet creates a thread to handle some request, such as a database query or a message connection, the thread waits until it gets the required resources before it can perform other operations. Asynchronous processing avoids this blocking by running threads to perform other operations. Apart from the features mentioned here, several other enhancements have been made to the existing API. The sections towards the end of the article will explore These features one by one in detail.

In addition to these new features, Servlet 3.0 also makes some improvements to the existing APIS, which we’ll cover at the end of this article.

Annotations are used in servlets

One of the major changes in Servlet 3.0 is support for annotations. Using annotations to define servlets and filters frees us from having to define corresponding entries in web.xml.

@WebServlet

@webServlet is used to define a Servlet in a Web application. This annotation can be applied to an inherited HttpServlet. This annotation has multiple attributes, such as Name, urlPattern, and initParams, which we can use to define the behavior of the Servlet. The urlPattern attribute must be specified.

The common container

Tomcat, Jetty, Resin, Oracle Application Server, WebLogic Server, Glassfish, Websphere, JBoss and so on. The server that provides Servlet functionality is called the Servlet container. For Web applications, the Servlet container functions as an operating system for desktop applications, providing some programming infrastructure.)

advice

In a Web application, a Servlet may be accessed by multiple users at the same time. The Web container will then create a thread for each user to execute the Servlet. If servlets don’t involve sharing resources, don’t worry about multithreading. But if servlets need to share resources, they need to be thread-safe.

Here are some suggestions for writing thread-safe servlets:

• Use local variables of a method to hold proprietary data in the request. For local variables defined in a method, each thread entering the method has its own copy of the method variable. No thread modifies the local variables of another thread. If you want to share data between different requests, you should use sessions to share such data.

• Use only member variables of the Servlet to hold data that will not change. Some data, which does not change during the life of a Servlet and is usually determined initially, can be stored using member variables, such as database connection names, paths to other resources, and so on.

• Synchronize member variables that may be requested to be modified. Sometimes data member variables or environment attributes may be requested to be modified. This data should be synchronized when accessed to avoid multiple threads modifying it at the same time.

If servlets access external resources, they need to be accessed synchronously. For example, suppose a Servlet reads and writes data from a file. When one thread reads or writes to a file, other threads may also be reading or writing to the file. File access itself is not thread-safe, so you must write code to access these resources synchronously. The following two methods should not be used when writing thread-safe servlets:

• A SingleThreadModel interface is provided in the Servlet API, which implements servlets that have only one thread running at a time when requested by multiple clients. This interface has been flagged as not recommended.

• Synchronize doGet() or doPost() methods. If you must use synchronized code in servlets, try to synchronize on the smallest possible block of code. The smaller the synchronization code, the better the Servlet will perform.

Servlets provide a component-based, platform-independent way to create Web-based applications without the performance constraints of CGI programs. The Servlet has access to all Java apis, including the JDBC API for accessing enterprise-level databases.