[Introduction to Servlet] An article that you have never heard of

foreword

In the last article, we learned the XML part of Java Web. If you don't know anything about XML, then you can go to this article, which can make you get started with XML quickly.

Portal: Quick Start to XML

Next, we officially start to learn Servlet.

Servlet overview

basic concept

Servlet (Server Applet), the full name of Java Servlet. It is a server-side program written in Java. Its main function is to browse and modify data interactively and generate dynamic Web content. Servlet in the narrow sense refers to an interface implemented by the Java language, and Servlet in the broad sense refers to any class that implements the Servlet interface. In general, people understand Servlet as the latter.

This concept is too abstract, let's learn servlet from the role of servlet!

Servlet working mode:

(1) The client sends a request to the server
(2) The server starts and calls the servlet, the servlet generates the response content according to the client request and transmits it to the server
(3) The server returns the response to the client

From this process, we can know what servlet does. My own understanding is a key hub for front-end and back-end interaction in web development.

Tomcat

At this point, we have to mention Tomcat, and we can't do without it for learning servlets.

Tomcat is a Web application server and a Servlet/JSP container. As a servlet container, Tomcat is responsible for processing client requests, sending requests to Servlets, and sending Servlet responses back to clients. Servlets are a kind of Servlet that runs in Java language. components on the server.

We only know that the request sent by the client is the request, and we use the response when we respond back. I don't know how it changed in this process, ignore the details, let's explore it now.
insert image description here
From this figure we know:

(1) Tomcat receives and parses the http request text, and then encapsulates it into a request object of type HttpServletRequest. All HTTP header data can be queried by calling the corresponding method on the request object.
(2) Tomcat will also encapsulate the information to be responded as a response object of type HttpServletResponse. By setting the response attribute, you can control the content to be output to the browser, and then hand the response to tomcat, and tomcat will turn it into the response text. format sent to the browser.

So how do we use servlets?

How to use servlet:

The core of servlet technology is servlet, which is an interface that all servlet classes must implement directly or indirectly. When writing a servlet class that implements a servlet, implement it directly. When extending a class that implements this interface, implement it indirectly.

The Java Servlet API is the interface between the servlet container (tomcat) and the servlet. It defines various methods of servlet, and also defines the object class that the servlet container transmits to the servlet, the most important of which are ServletRequest and ServletResponse. So when we write servlet, we need to implement the servlet interface and operate according to its specifications.

In addition to this, we have to install tomcat to turn our computer into a micro server so that it can respond during your practice.

Tomcat installation and configuration tutorial

The first servlet

After we install the software and configure the environment, we can write our first servlet.

We create a class and inherit the HttpServlet class, and then rewrite the service method in it. In this process we need to import the corresponding package.

HttpServletRequest refers to the request sent by the client to the server, and HttpServletResponse refers to the response returned by the server to the client.

import java.io.IOException;
import java.io.PrintWriter;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class FirstServlet extends HttpServlet{
    
    
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
		//接受请求发来的参数
		String name = request.getParameter("name");
		//服务器返回的响应
		String html = "<h1 style='color:red'>hi,"+ name +"!</h1><hr/>";
		PrintWriter out = response.getWriter();
		out.println(html);
	}

Only this Java file is not enough. You just wrote this, and the service does not know what your request is. We have to declare Servlet.

Open the web.xml file with the following path
insert image description here
We have to write the declaration in the following place.
insert image description here
The statement is as follows:

	 <!-- 声明Servlet -->
	<servlet>
	<!-- servelt的别名 -->
		<servlet-name>first</servlet-name>
		<servlet-class>com.imooc.servlet.FirstServlet</servlet-class>
	</servlet>
	
	<!-- 将Servlet与URL绑定 -->
	<servlet-mapping>
		<servlet-name>first</servlet-name>
		<url-pattern>/hi</url-pattern>
	</servlet-mapping>

insert image description here

After saving, we can publish it on the server. Right-click on our Tomcat and select Add and Remove.
insert image description here
Select FirstServlet and click Add to publish.
insert image description here
After finding that FirstServlet reaches the right, we can click Finish.
insert image description here
After expanding tomcat, we will find that our FirstServlet is under its directory. Then we select tomcat, and then click on the little bug (debug) on ​​the right.
insert image description here
When we see the following, our server starts successfully.
insert image description here
Then open the browser and enter localhost:8080/FirstServlet/hi?name=baibai

Where localhost:8080 represents the local port, FirstServlet is our project name, hi is the alias set when our servlet is bound to the URL, ? It represents the parameters behind, and the name is also the parameter table we wrote in the Java file. The parameters we pass in are white.

The corresponding server also responded according to the Java file we wrote.
insert image description here
insert image description here
So far our first servlet has been successfully run and released.

Servlet development and basic configuration

We have successfully completed our first servlet above, so what are the basic steps for us to develop a servlet? Let you say it all at once, you may be a little messy, so let's summarize it!

In fact, we just went through the following steps when we wrote our first servlet:

(1) Create a Servlet class, inherit HttpServlet
(2) Rewrite the service method of HttpServlet, write program code
(3) Configure web.xml, bind URL

After knowing these steps, you are revisiting the development process of our first servlet to see if this is the case.

After we write the servlet, we all need to access the servlet to check whether the output is normal, so how do we access it? The following access methods are what you should know.

(1) http://IP address: port/context-path/url-mapping
(2) Remote access uses IP address, local access localhost (127.0.0.1)
(3) context-path becomes "context path", the default is Construction name

As before,
insert image description here
after reading this, you should understand.

Servlet life cycle

In such a short process, Servlet actually went through the process of birth, work, and death like a human being. Among them, init( ), service( ), destroy( )are the methods of the Servlet life cycle.

Represents the process of Servlet from "birth" to "work" to "death". A servlet container (such as TomCat) will call these three methods according to the following rules:

(1) init( ) method: When the servlet is requested for the first time, the servlet container will start calling this method to initialize a servlet object, but this method will not be called by the servlet container in subsequent requests. We can use init()methods to perform the corresponding initialization work. When calling this method, the servlet container will pass ServletConfigin an object Servletto initialize the object.
(2) service( ) method: Whenever a servlet is requested, the servlet container will call this method. When the first request is made, the servlet container will first call the init()method to initialize a servlet object, and then call its service()method to work, but in subsequent requests, the servlet container will only call the service method.
(3) destroy() method: When the servlet is to be destroyed, the servlet container will call this method. This happens when the application is uninstalled or the servlet container is closed. Generally, some cleanup code is written in this method.

First, let's write a simple servlet to verify its life cycle:

We directly transform the FirstServlet class just now. We not only rewrite the service()method but also rewrite other methods. The code is as follows:

import java.io.IOException;
import java.io.PrintWriter;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class FirstServlet extends HttpServlet{
    
    

	//构造方法
	public FirstServlet() {
    
    
		System.out.println("正在创建FirstServlet对象");
	}
	
	@Override//初始化方法
	public void init() throws ServletException {
    
    
		System.out.println("正在初始化FirstServlet对象");
	}

	@Override//响应方法
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

		//接受请求发来的参数
		String name = request.getParameter("name");
		String html = "<h1 style='color:red'>hi,"+ name +"!</h1><hr/>";
		System.out.println("返回给浏览器的响应数据为:"+html);
		PrintWriter out = response.getWriter();
		out.println(html);
	}

	@Override//销毁方法
	public void destroy() {
    
    
		System.out.println("正在销毁FirstServlet对象");
	}
}

After writing, save it, and then continue to start the server.
insert image description here
At this time, because we have not sent a request to the server, so we have not created an object yet. After we send a request to the server in the browser:
insert image description here
these three outputs indicate that the first servlet class has been created. object, and call the construction method, initialization method, and service method of FirstServlet in turn.

If we make changes to the content in FirstServlet, then this object will be destroyed, as follows:
insert image description here

Annotations simplify configuration

Everyone should have noticed that every time we create a new servlet class, we have to configure it in web.xml, which is really troublesome, so is there any way to simplify the operation? The answer is yes, that is to use annotations.

Simplify the configuration of Servlet classes in web.xml through annotations: Before using annotations, you need to configure in web.xml every time you create a new Servlet class, and you do not need to configure in the web.xml file after use.

Next, let's introduce the use of annotations!

The "Annotation Annotation" feature was introduced after Servlet 3.x. Annotations are
used to simplify the configuration process of web applications.
Servlet core annotations: @WebServlet

Use demo:

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/anno")//映射地址
public class AnnotationServlet extends HttpServlet{
    
    

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
		response.getWriter().println(" I'm annotation servlet!");
	}

}

Output:
insert image description here
In the above servlet, I did not go to web.xml to configure it, but he still publishes the output normally because we use annotations.

Load servlet at startup

It is very common to load this scene at startup. For example, when playing the glory of the king, does it have to be loaded for a while after the hero is selected to officially start the canyon tour? This is the same.

Why should servlets be loaded at startup?

The servlet object is created when it is accessed for the first time, and the init method is executed. Suppose some time-consuming operations are done in the init method (eg: some configuration files are loaded and parsing may take 3 seconds). When the first user accesses the servlet for the first time, it needs to wait 3 seconds. How can I make it not take so long for the first user to visit for the first time?

What is the startup load of a servlet?

By default, the Servlet object is created when it is accessed for the first time. Now, through a configuration, the instantiation process of the Servlet is placed when the server starts (let the Servlet object be created when the server starts). If you do this now then the time spent will be spent when the server starts. For the user, there is no need to spend this extra time.

How to configure the servlet to load at startup?

In web.xmlthe tag corresponding to the file (in the servlet tag where the name and full class path are set) <servlet>. You can configure a label that is automatically loaded at startup. The label is <load-on-startup>5</load-on-startup>that this class file will be loaded directly when the server starts. The integer in the middle is: the smaller the integer, the higher the loading priority, generally it cannot be less than 2.

It may be a little confusing after reading, so let’s summarize!

web.xmlUse <load-on-startup>settings to start loading
Range: <load-on-startup>0~9999 </load-on-startup>
Load at startup is commonly used for preprocessing of the system at work

Epilogue

These are some uses of Servlet foundation, and the whole knowledge system will be gradually improved in the future, thank you for reading.

Continually updated…

Guess you like

Origin blog.csdn.net/apple_51673523/article/details/122732956