Hello, today I would like to share with you the introduction of Servlet, take out a small notebook to write down!

1. What is a Servlet?

Web projects that want to run on web servers (TomCat, JBoss, etc.) must meet a set of rules, and servlets are rules

This set of rules was developed by SUN Corporation (the core of the Servlet specification is the Servlet interface) and belongs to the JAVA EE specification, and we JAVA programmers write the implementation classes of servlets

2. Roles and functions of Web projects

Web server:

Manage web projects according to certain rules

Find the corresponding Web item based on the browser URL

SUN:

SUN is the architect of the rules of interaction between Web servers and Web projects

It specifies the Servlet interface that programmers must implement if they want web servers to manage their own resources

Java programmers developing Web projects:

Write the Servlet interface implementation class, write the configuration file XML (binds the user’s request path to the underlying Java program)

The following three lines simulate an XML file

        /login=LoginServlet

        /delete=DeleteServlet

        /save=SaveServlet

XML files for Web projects are saved in a form similar to path = resource (class name)

When a user enters a resource, the Web server can find the corresponding resource value based on the path (key).

The new object is then reflected by the class name (resource)

3. Introduction to Servlet specifications

1. Servlets are a macro specification derived from one of the JavaEE specifications

2. How it works:

In the Servlet specification, specify the “dynamic resource file” development step

In the Servlet specification, specify that the Web server invokes dynamic resource file rules

In the Servlet specification, specify rules for the Web server to manage dynamic resource file instance objects

4. Servlet interface implementation class

1. The Servlet interface is derived from the interface under the Servlet specification, which exists in the JAR package provided by the Web server

Javax.servlet.servlet interface (javax.servlet.servlet interface)

3. According to the Servlet specification, the dynamic resource file that the Web server can call must be a Servlet interface implementation class

5. Servlet interface implementation class development steps

Step 1: Create a Java class that implements the Servlet interface

The subclass relationship of the Servlet interface is as follows

Parent interface Servlet—— grandparent class GenericServlet(abstract)—— parent class HttpServlet(abstract)—— subclass Implementation class written by Java programmers

The Servlet interface has five abstract methods (the most important being Services)

The GenericServlet class does not implement service; everything else does

The HttpServlet class implements a Service Method. In a Service, request.getMethod() is used to get the name of the Method on the request side (get, POST, etc.), not reflection.

Java programmers write implementation classes that override concrete doXXX methods

This example shows one function of abstract classes:

Reduce the dependency of interface implementation classes on interfaces by inheriting interfaces from abstract classes (abstract classes implement some abstract methods in interfaces) (interface implementation classes can directly inherit abstract classes that have implemented some methods, rather than inheriting interfaces that have implemented nothing)

The main reason for inheriting the HttpServlet interface rather than implementing it directly is to simplify the development process

Step 2: Override the two methods in the HttpServlet parent class,doGet or doPost

The Web server will find the corresponding implementation class according to the path name, create an object through reflection, and call the service method of this object actively by the Web server

In the implementation class, the doGet or doPost methods are overridden, and the implementation class inherits the Service method implemented by the HttPServlet class.

Reflection gets the method name on the request side and invokes the corresponding doXXX method

Step 3: < register > the Servlet interface implementation class information to the Web server

In this way, the Web server can follow the path to find the corresponding implementation class and complete the relevant operations.

Web. XML Path: Web project file —-web—- web-INF –web.xml

Find the file and add it as follows:

        

            mm

        

            oneServlet

            

        

            

        

            mm

        

            /one

            

The request URL is: http://localhost:8081/web project name/one, access to resources for the project name in class oneServlet IDEA can be in the run – edit – Application on the bottom of the Deployment context changes

6. Lifecycle of Servlet objects (how web servers manage Web projects)

1. All servlet interface implementation class objects in a Web site (Web project) must be created by the Web server (reflection)

2. By default, when the Web server receives the first request for the current Servlet interface implementation class, it automatically creates an instantiation object for that Servlet interface implementation class

In the case of manual configuration, you can require the Web server to create an instantiation object of the class at startup

Set this manually in the web.xml configuration file

            mm

            oneServlet

            

            30

            

3. Only one instance object can be created from a Servlet interface implementation class while the Web server is running

4. Automatically destroy all Servlet objects in the web site when the Web server is down

7. The HttpServletResponse interface

1. Introduction

  1. The HttpServletResponse interface is derived from the Servlet specification and exists in Servlet-api.jar in Tomcat

  2. The implementation class for the HttpServletResponse interface is provided by the Web server

  3. The HttpServletResponse interface is responsible for writing the results of the doGet/doPost method execution to the response body for the browser

  4. Developers are used to calling the objects instantiated by the HttpServletResponse interface response objects

2. Main functions

  1. Write execution results in binary form to the response body (serialization and deserialization)

Ex. :

2. You can set the content-Type attribute value of the response header to control the browser to use the corresponding compiler to compile the binary data of the response body into the corresponding text, image, video, etc

Ex. :

Instead of 50, the browser displays 2

The reason:

Out.writer (), which can write characters, strings, and ASCII codes to the response body

When the argument is int, it is assumed to be ASCII, and the browser prints the corresponding ASCII character

When the ASCII code is 50, the corresponding character is 2

Solution:

Use out. Print ();

Therefore, out.print() method should be used in future development, writer().

Ex. :

The result on the browser is: Java

JavaScript

C??

The browser doesn’t treat our response package as HTML, it treats it as plain text

Cause: After receiving the response package, the browser uses a different compiler to compile the binary content in the response body based on the value of the content-Type attribute in the response header

On the default request, our Content-Type property has a value of “text”, at which point the browser uses the text compiler to parse the binary value

Solution: Reassign the Content-Type attribute in the response header through the response object to the corresponding binary compiler before getting the output stream

I’ve solved the HTML problem, but I still have it in the result, okay? So let’s grab a package and look at the value of content-type, content-type: text/ HTML; charset=ISO-8859-1

Change the character set

response.setContentType(“text/html; charset=UTF-8”);

It turns out all right, nice

Content-type :text/ HTML; Charset = utF-8 3. Set the location property of the response header and assign a request address to location to control the browser to send a request to the specified server

After the browser receives the response packet, if it finds the location attribute in the response header, it automatically sends the request to the location specified by location through the address bar

The sendRedirect method controls the behavior of the browser remotely

Request three elements: request address, request mode, request parameters

Request parameters can be appended to the URL as a queryString

Ex. :

8. It interfaces

1. Introduction

  1. The HttpServletRequest interface is derived from the Servlet specification and exists in Servlet-api.jar in Tomcat

  2. The implementation class for the HttpServletRequest interface is provided by the Web server

  3. The HttpServletRequest interface is responsible for reading the information in the Http request protocol packet when the doGet/doPost method runs

  4. Developers are used to calling the objects instantiated by the HttpServletRequest interface request objects

  5. HTTPServletRequest extends ServletRequest{}

  6. What information does HTTPServletRequest encapsulate?

Request method

URI

Protocol Version number

Form submission data

.

  1. Each request corresponds to one HttPServletRequest

2. The role

  1. You can read the information in the Http request line (the first line of the request, including the request method, URL, and Http protocol version) in the Http request package

Ex. :

Print on the console:

        URL = http://localhost:8081/05/one

        method = GET

The {URI} information in {request line} can also be read from the request object

Request.getrequesturi (), reads the URI and returns a string

URI: The resource file locates the exact address. This property is not actually present in the request line, but is actually a string taken from the URL

This string is in the format of “/ Web project name/resource name”

Uris are used to allow web servers to locate accessed resources

Ex. :

// 3. Read {URI} in {request line} from the request object

// request.getrequesturi (), reads the URI information and returns a String

        String uri = request.getRequestURI();

        System.out.println(“URI = ” + uri);

2. The parameters stored in the Http request header or request body can be read. For example, a static resource (HTML file) is created in a Web project.

Access TwoServlet via hyperlink with request parameters

        

The simulated access to a resource is accompanied with parameter information, which can be seen as username and password/two paths. The corresponding Servlet interface implementation class is as follows:

The result printed on the console is :userName=Tompassword=123 The above example obtains a QueryString from the request header, the following from the request body

            

The user name

            

            

        

The Servlet implementation class for this form submission path is as follows:

public class ThreeServlet extends HttpServlet {

            protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// Read the parameters of {request body} from the request object

// The method is exactly the same as in the request header

            String value = request.getParameter(“username”);

            System.out.println(“username = ” + value);

            }

        }

Type Zhangsan on the form

The output on the console is as follows:

username = zhangsan

You can see that the code is the same whether the queryString information is retrieved from the header or the body of the request

However, if the queryString in the POST method has Chinese characters, garbled characters will appear

The reason: The browser sends the request as Get, and the parameters are stored in the request header. When the Http request packet arrives at the Web server (the content in the packet is binary), the first thing to do is decode it

The binary content in the request header is decoded by Tomcat, using UTF-8 by default

If the request is posted, the parameters are stored in the request body, and when the Http request packet arrives at the Web server (the contents of the packet are binary), the first thing to do is decode it

The binary content in the request body is decoded by the request object (REQUEST). The request object (REQUEST) uses the ISO-8859-1 character set by default

Solution: Inform the request object to decode with utF-8 character set before reading the request body content

To be on the safe side, we will override the doGet and doPost methods by adding the following code to the first two lines to specify the decoding method

request.setCharacterEncoding(“UTF-8”);

response.setCharacterEncoding(“UTF-8”);

  1. Can request resource file calls from the Web server instead of the browser

That’s redirection

3. Form submission data format

Example: the username = admin&password = 123 & interest = sport&interest = music

As you can see from the above example, the form submits data information in a key-value pair format

Key-value pairs can be abstracted as maps, but we find that interest corresponds to two values (a name in a checkbox may correspond to multiple values)

So the Map format is <String, String[]>

The Map format of the above example is as follows:

Map<String, String[]>

        —————————————-

        key         value

        username    {“admin”}

        password  {“123”}

        interest  {“sport”, “music”}

4. Common methods

Form submitted data is automatically encapsulated in the Request object, which has a Map<String, String[]> to store the data

String getParameter(String name) // Get the first element of the corresponding value(String[]) by key

Map getParameterMap() // Gets the entire Map set

Enumeration getParameterNames() // Get all keys of the entire Map set

String[] getParameterValues(String name) // Get the corresponding value(String[]) by Key. This method is suitable for getting check box request information

Obtain path address

String getRemoteAddr() // Obtains the CLIENT IP address

String getContexPath() // Get the context path (web project root path)

String getMethod() // Get request method

String getRequestURI() // Get the URI

StringBuffer getRequestURL() // Gets the URL

String getServletPath() // Get the Servlet path, where the path refers to the path associated with the web.xml and the Servlet implementation class (/ XXX)

To store information to a request, see the following 5. What scope is HttpServletRequest

Void setAttribute(String name, Object O) // Stores data to the request scope. Name is the key and O is the value, similar to Map

Object getAttribute(String name) // Reads data from the Request scope

Void removeAttribute(String name) // Removes data from the Request scope

Get the request forwarder and point the forwarder object to a resource, using the parameter “/ XXX “configured in the web.xml file

5. What scope is HttpServletRequest

RequestDispatcher getRequestDispatcher(String path)

Methods related to the session

Cookie[] getCookies()

            HttpSession getSession()

5. What scope is HttpServletRequest

An object of type HttpServletRequest is usually named Request, representing the request

Each request corresponds to a request object. The request scope is very small, and the request can only complete the data transfer in the same request

Consider the following example: AServlet stores objects to request and then retrieves them

At this point, the browser prints: User{usercode=’111′, username=’zhangsan’} If BServlet is asked to fetch data from the Request after the above operation is completed

The BServlet class is as follows:

The result displayed on the browser is NULL

This shows that the request of these two servlets is not an object solution: forward

Change AServlet to the following, and leave BServlet unchanged

User{usercode=’111′, username=’zhangsan’}

Note that AServlet does not print to the browser, but BServlet does, indicating that the data was retrieved by forwarding BServlet

If we take a look at the packet, we find that there is only one request, which means that forwarding is only one request

9. Lifecycle of request object and response object

  1. After the Web server receives the Http request packet sent by the browser, it automatically generates a request object and a response object for the current Http request packet

  2. When the Web server calls the doGet or doPost method, it is responsible for passing the request object and the response object as arguments to the method to ensure that doGet/doPost is executed correctly

  3. When doGet or doPost runs, the request is processed and the Web server generates an HTTP response packet.

So the life cycle of the request object and the response object runs through the process of a request

The request object parses the contents of the request packet, and the response object tells the result of the doGet/doPost method.

So [request object] and [response object] are more like hitchhikers between the Web server and the browser (or the user)

Well, that’s all for today’s article, hoping to help those of you who are confused in front of the screen