Home  >  Article  >  Java  >  How to implement Servlet in Java

How to implement Servlet in Java

PHPz
PHPzforward
2023-05-17 11:34:50873browse

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.0In 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>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 ServletAPI 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 Servlet instance 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 GET request, Then call the doGet() method; if it is a POST request, call the doPost() method;

if If the subclass overrides the

doXXX() method, the rewritten doXXX() method is called;

If the subclass does not override

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.

How to implement Servlet in Java

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到了");
	}
}

How to implement Servlet in Java

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete