Detailed explanation of the basic knowledge of servlets in Java
This article mainly introduces the relevant information on the basics of servlet in detail, which has certain reference value. Interested friends can refer to it
Servlet is a tool specifically used to develop dynamic web resources. technology, Sun provides a Servlet interface in its API (of course, we will not directly implement this interface, but it will be better to inherit its implementation class). Therefore, Servlet in the narrow sense refers to this interface, and in the broad sense, Servlet refers to this interface. Servlet refers to any class that implements this Servlet interface. Using Servlet to develop a dynamic web resource is actually developing a Java program to output data to the browser.
Servlet is actually a Java program that runs on the server. Servlet is one of the thirteen technologies of J2EE. Therefore, we cannot read the J2SE API documentation. If you are a beginner, it is best to read the specialized Servlet API documentation. Let’s take a look at the document introduction of Servlet:
From this introduction to the Servlet interface, we can see that if you want to implement the Servlet interface, you must implement all its methods. Servlet The program runs on the web server and is used to receive and respond to requests from clients. Of course, as I said before, if you write a class to implement the Servlet interface, you will have to override all the methods of the Servlet, but we can inherit its implementation class, such as the GenericServlet class or the HttpServlet class, so that we only need to override the ones we want to override. Just use the method.
The methods in Servlet include its life cycle methods and non-life cycle methods. In Servlet, life cycle methods include: init(ServletConfig config), destroy(), service(ServletRequest req, ServletResponse res), that is, Servlet initialization, response service to requests, and destruction of Servlet.
In addition to the Servlet life cycle methods, there are also non-life cycle methods, such as getServletConfig() and getServletInfo() methods, which can obtain some information about the Servlet.
The Servlet life cycle refers to the process from creation to responding to client requests and finally destruction of a Servlet instance. The specific process is as follows:
1. Server creates an instance of Servlet, that is, calls the init() method;
2. A client request (object) reaches the Server;
3. Server sends the request to Servlet;
4. Servlet generates a response (object) to the request;
5. Server activates the service() method of Servlet, passing the request object and The response object is used as a parameter;
6. The Service() method obtains the information of the request object, processes the request, accesses resources, and obtains the required information;
7. The Service() method uses the response object method, the response is sent back to the server and finally reaches the client. The Service method may also activate other methods to process requests, such as the doGet() or doPost() method;
8. For more client requests, the Server creates new request and response objects and still activates this Servlet. service method, pass these two objects to it as parameters, without calling the init() method. Generally, Servlets are only initialized once. When the Server no longer needs the Servlet (usually the Server is shut down), the Server calls the Servlet's destroy() method to destroy the Servlet.
As can be seen from the above, the three methods in the Servlet life cycle are called by the server, which can be said to be at a certain moment in the process from the beginning of the Servlet's existence to its destruction (if an event is triggered) The method that must be executed is called a life cycle method.
Therefore, the most important thing in Servlet is the service() method. If you want to transfer resources from the server back to the client or send data to the client, you will do it in the service() method. .
Judging from the service(ServletTequest req, ServletResponse res) method, not only the service() method is called and executed by the server, but also the ServletTequest request object and ServletResponse response object are also provided by the server. If we want to write a simple After the data is given to the client, you can operate the ServletResponse response object in the service() method:
As a starter, we don’t need to use the development tool IDE to write the Servlet, but write it manually first, which will help to understand the Servlet. underlying principles. Create my web application in the [webapps] directory of Tomcat. The directory where the web application is located is [myservlet]. We first create [WEB-INF] in the [myservlet] directory, and then create [classes] in [WEB-INF]. ] directory, [lib directory] and web.xml file, in the [classes] directory, create my Java program: FirstServlet.java
Because the Servlet we write is called by the server, the Servlet implementation class we create must be public. Let me start by saying that we do not need to implement all the methods of the Servlet, so we ask the client To transfer data, we only need to override the service() method. Then we only need to inherit the implementation class of Servlet, and then obtain the output stream of the corresponding object ServletResponse ServletOutputStream to output data to the client. At the same time, because the output is Byte stream, so you need to convert the characters into a byte array, and then manually write the custom package name and the Java package to be imported:
package fjdingsd.web; import java.io.*; import javax.servlet.*; public class FirstServlet extends GenericServlet{ public void service(ServletRequest req, ServletResponse res) throws ServletException, java.io.IOException { OutputStream out = res.getOutputStream(); out.write("Hello Servlet".getBytes()); } }
Use cmd to run this Java program Compile, but be aware that "javac" only imports the J2SE package by default, but does not include the J2EE package. So where do we go to find the J2EE Servlet package? In fact, because Tomcat supports Servlet, Tomcat's [lib] directory contains the Servlet JAR package:
So we should first perform this step in cmd to set the environment variable: set classpath = %classpath%; path/servlet-api.jar
Then you can compile the Java program just now: javac –d. Program name.java
("-d" represents the directory where the .class file is stored for the next command, and "." represents the current directory)
After the compilation is successful, you can see that there are bytecodes in the directory where the web application is located. The file and package names are:
Of course, there is already a Servlet program, but the browser cannot access it yet because the Servlet program has not yet set an external access path. So where do we configure the Servlet bytecode file we just created into a path that the browser can access?
The answer is in the web.xml file in this web application. Now we only take the simplest format. As mentioned in "Tomcat Detailed Learning Method (3)", change Tomcat's web.xml Copy the header and tail in the "template" into your own web. The
At this time, open the Tomcat server and you can access the Servlet program you just wrote in the browser. The input format is: host name: port (80 does not Required)/web application name/external access path
If it is for Servlet access, then you only need to write the external access path. If you write the name of the Servlet, it is also Inaccessible, as shown below:
There is another problem. If the external access paths of multiple Servlets in the xml file are configured the same, they will also be inaccessible, as follows Figure:
Therefore, please configure different external access paths in custom web.xml for different Servlets.
The above is the detailed content of Detailed explanation of the basic knowledge of servlets in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
