How to implement Servlet in Java
Web Basics and HTTP Protocol
┌─────────┐ ┌─────────┐ │░░░░░░░░░│ │O ░░░░░░░│ ├─────────┤ ├─────────┤ │░░░░░░░░░│ │ │ ├─────────┤ │ │ │░░░░░░░░░│ └─────────┘ └─────────┘ │ request 1 │ │─────────────────────>│ │ request 2 │ │─────────────────────>│ │ response 1 │ │<─────────────────────│ │ request 3 │ │─────────────────────>│ │ response 3 │ │<─────────────────────│ │ response 2 │ │<─────────────────────│ ▼ ▼
We noticed that the HTTP protocol is a request-response protocol, which always sends a request and then receives a response. Can I send multiple requests at once and then receive multiple responses? HTTP 2.0
can support the browser to issue multiple requests at the same time, but each request needs a unique identifier. The server can return multiple responses not in the order of the requests, and the browser itself can match the received responses with the requests. stand up. It can be seen that HTTP 2.0
further improves transmission efficiency, because after the browser sends a request, it does not have to wait for a response before it can continue to send the next request.
HTTP 3.0
In order to further improve the speed, the TCP
protocol will be abandoned and replaced with the UDP
protocol that does not require the creation of a connection. Currently HTTP 3.0
is still in the experimental promotion stage.
What is Servlet
On the JavaEE
platform, all the underlying work of processing TCP
connections and parsing the HTTP
protocol is thrown away To do it for the ready-made Web
server, we only need to run our own application on the Web
server. In order to achieve this purpose, JavaEE
provides Servlet
API
, we use Servlet API
to write our own Servlet
To handle HTTP
requests, Web
server implements Servlet
API
interface,
implements underlying functions.
// WebServlet注解表示这是一个Servlet,并映射到地址 hello.do @WebServlet(urlPatterns = "/hello.do") public class HelloServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 设置响应类型: resp.setContentType("text/html"); // 获取输出流: PrintWriter pw = resp.getWriter(); // 写入响应: pw.write("<h2 id="Hello-nbsp-world">Hello, world!</h2>"); // 最后不要忘记flush强制输出: pw.flush(); } }
A Servlet
always inherits from HttpServlet
, and then overrides doGet()
or doPost()
method. Notice that the doGet()
method passes in two objects, HttpServletRequest
and HttpServletResponse
, which represent the HTTP
request and response respectively. When we use Servlet API
, we do not interact directly with the underlying TCP
, nor do we need to parse the HTTP
protocol, because HttpServletRequest
and HttpServletResponse
has already encapsulated the request and response. Taking sending a response as an example, we only need to set the correct response type, then get PrintWriter
and write the response.
Such a project will eventually be packaged into a *.war
file. To run this file, you need to use the Web that supports Servlet
API
Container (web server).
Therefore, we first need to find a web server that supports Servlet API.
Commonly used servers are:
Tomcat: an open source free server developed by Apache;
Jetty: an open source free server developed by Eclipse;
GlassFish: an open source, full-featured JavaEE server.
The life cycle of Servlet
In the process of initiating a Servlet
request through a URL
path, its essence It is calling the doXXX()
method that executes the Servlet
instance. The process of creating and using the Servlet
instance is called the Servlet life cycle. The entire life cycle includes: instantiation, initialization, service, and destruction.
Instantiation: Find the ## based on the path requested by
Servlet
(for example:home.do
)Instance
of #Servlet. If the instance does not exist, the creation of the Servletinstance is completed by calling the constructor method.
Initialization: Through the instance of the
Servlet
, call the init()method, Execute initialization logic.
Service: Through the instance of the
Servlet
, call the service()method, If the subclass does not override this method, the
service()method of the HttpServlet parent class is called, and the request method is judged in the method of the parent class. If it is a
GETrequest, Then call the
doGet()method; if it is a
POSTrequest, call the
doPost()method;
doXXX() method, the rewritten
doXXX() method is called;
doXXX () method, the
doXXX() method of the parent class is called. In the method implementation of the parent class, an error page with the
405 status code is returned.
405 status code: Indicates that the requested method is not supported by the server.
4. Destruction: When the server is shut down or restarted, all Servlet instances will be destroyed, and the destroy() method of the Servlet instance will be called.
package com.my.hyz.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //@WebServlet("/home.do") public class HomeServlet extends HttpServlet { public HomeServlet() { System.out.println("实例化"); } @Override public void init() throws ServletException { System.out.println("初始化"); //super.init(); } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("调用Service实例"); } @Override public void destroy() { System.out.println("销毁咯!!!!"); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("哎呦get到了"+this.hashCode()); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("哎呦post到了"); } }
The above is the detailed content of How to implement Servlet 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

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.

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