Servlet learning phase I

What is a servlet

1. Servlet is one of the Java EE specifications. A specification is an interface.
2. Servlet is one of the three major components of Java Web. The three components are: servlet program, Filter filter and Listener listener.
3. Servlet is a java applet running on the server. It can receive requests sent by the client and respond to data to the client.

Important: the servlet can receive the request sent by the client and respond to the data to the server.

Servlet first experience

1. Write a class to implement the Servlet interface
2. Implement the service method, process the request and respond to the data
3. To the web XML to configure the access address of the servlet program

Now let's implement this. First, create a Java EE project:

Then, in the first step, we write a class in the src directory to implement the servlet interface and the methods prepared for us in the servlet interface:

package com.atguigu.servlet;

import javax.servlet.*;
import java.io.IOException;

public class HelloServelt implements Servlet {
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        
    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {

    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {

    }
}

Here we focus on the service method, because this method is used to execute our data request and response. Here we print a sentence: Hello Servlet has been accessed.

@Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("Hello Servlet Was interviewed");
    }

Then the third step, we go to the web Configure the access address of the servlet program in the XML configuration file, otherwise Tomcat does not know the servlet program.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--servlet Label to Tomcat to configure Servlet program-->
    <servlet>
        <!--servlet-name Label to servlet The program has an alias (usually a class name)-->
        <servlet-name>HelloServlet</servlet-name>
        <!--servlet-class yes servlet The full class name of the program-->
        <servlet-class>com.atguigu.servlet.HelloServelt</servlet-class>
    </servlet>

    <!--servlet-mapping Label to servlet Program configuration Tomcat Access address for-->
    <servlet-mapping>
        <!--servlet-name The tag is used to tell the server to which address I currently configure servlet Program use-->
        <servlet-name>HelloServlet</servlet-name>
        <!--url-pattern Label configuration access address
            /What does it mean?
            Indicates that when the server resolves, the address is: http://ip:port / Project path

            /hello What does it mean?
            Indicates that the address is: http://ip:port / Project path / hello
        -->
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

</web-app>

Then we start Tomcat, and you can see that the default value of 8080 is $END$

Then we visit hello:

You can see that the console prints the following information:

Common errors

1. The path configured in the URL pattern does not begin with a slash.

2. The value of servlet name configuration does not exist:

3. Servlet class tag full class name configuration error:

Access procedure from url address to Servlet address

Life cycle of Servlet

It refers to some methods that will be called during the execution of the whole Servlet program. These methods exist in the Servlet interface (refer to the HelloServlet code above):

1. Execute Servlet constructor method
2. Execute init initialization method
The first and second steps above are to create a Servlet program and call it during the first access.

3. Execute the service method
The third step is to call every access.

4. Execute destroy destroy method
Step 4: call when the web project stops.

Distribution processing of GET and POST requests

From the above learning, we know that there is only one service method in the servlet, but we have more than one request, such as GET and POST. So how to distribute these two requests?
Let's first write a form under the web project:

After the above form is submitted, it will jump to the hello address page of our HelloServle.

However, we know that if the request mode is different, the form must do different things, but we only have one service method in a servlet program. How to deal with the two requests?

One method is to get the name of the current request method through the getMethod() method in the ServletRequest of ServletRequest type.

Here is a trick in idea. You can quickly view the inheritance and implementation system of the current class with ctrl+h.

However, it should be noted that our ServletRequest is an interface, and it does not have a corresponding implementation class, so we cannot directly use the instance of ServletRequest to call the getMethod method, but we can use its sub interface HttpServletRequest to get the getMethod() method, because the interface has an implementation class HttpServletRequestWrapper:

Then we try to write code to get the current request:

@Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        //Cast type to HttpServletRequest
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        //Then call the getMethod method through the instance object of HttpServletRequest type
        String method = httpServletRequest.getMethod();

        System.out.println("The current request method is:"+method);
    }

You can see the console output by accessing:

That means we succeeded.
Now we can realize the distribution processing of different request modes:

@Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        //Cast type to HttpServletRequest
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        //Then call the getMethod method through the instance object of HttpServletRequest type
        String method = httpServletRequest.getMethod();

        if("GET".equals(method)){
            System.out.println("implement GET Request operation");
        }else if("POST".equals(method)){
            System.out.println("implement POST Request operation");
        }
    }

But when we handle too many code operations in the request, writing in a service method will be very bloated, so we can separate the operation of different requests as a method, and then we will call it better in the service method.

@Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        //Cast type to HttpServletRequest
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        //Then call the getMethod method through the instance object of HttpServletRequest type
        String method = httpServletRequest.getMethod();

        if("GET".equals(method)){
            doGet();
        }else if("POST".equals(method)){
            doPost();
        }
    }
    //Method of processing get request
    public void doGet(){
        System.out.println("be-all get Request operation");
    }

    //Method of handling post request
    public void doPost(){
        System.out.println("be-all post Request operation");
    }

Implement Servlet program by inheriting HttpServlet

Generally, in the actual project development, the Servlet program is implemented by inheriting the HttpServlet class.
1. Write a class to inherit the HttpServlet class
2. Override doGet or doPost methods according to business needs
3. To the access address of the configuration Servlet program in web.xml

Let's do this:

package com.atguigu.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//1. First, write a class to inherit the HttpServlet class, which is an implementation class of the Servlet interface
//Because HttpServlet is more convenient to use than Servlet interface
public class HelloServlet2 extends HttpServlet {

    //2. Rewrite the request method in HttpServlet
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doGet(req, resp); this can be removed and rewritten
        System.out.println("doGet method");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doPost(req, resp); this can be removed and rewritten
        System.out.println("doPost method");
    }
}

Then go to web.xml to configure the address for HelloServlet2:

<!--to configure HelloServlet2 Mapping address-->
    <servlet>
        <servlet-name>HelloServlet2</servlet-name>
        <servlet-class>com.atguigu.servlet.HelloServlet2</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>HelloServlet2</servlet-name>
        <url-pattern>/hello2</url-pattern>
    </servlet-mapping>

Then you can test it.

Using the IDEA menu to quickly generate Servlet programs


Then configure the Servlet information:

Inheritance system of Servlet class

ServletConfig class

From the perspective of class name, ServletConfig class is the configuration information class of Servlet program.

Both the Servlet program and the ServletConfig object are created by Tomcat and used by us.

By default, Servlet programs are created during the first access. ServletConfig is to create a corresponding ServletConfig object when each Servlet program is created.

Three functions of ServletConfig class

1. You can get the value of the alias Servlet name of the Servlet program
2. You can get the initialization parameter init param
3. You can get the ServletContext object

Where is this class used? Go back to the HelloServlet class we wrote earlier. You can see that there are instance objects of the ServletConfig class in the implemented init method:

@Override
    public void init(ServletConfig servletConfig) throws ServletException {

    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

Let's test the above functions. Before testing, we have to go to the web Configure init param and ServletContext to be used later in XML:

<!--servlet Label to Tomcat to configure Servlet program-->
    <servlet>
        <!--servlet-name Label to servlet The program has an alias (usually a class name)-->
        <servlet-name>HelloServlet</servlet-name>
        <!--servlet-class yes servlet The full class name of the program-->
        <servlet-class>com.atguigu.servlet.HelloServelt</servlet-class>
        <!--init-param Is an initialization parameter. The parameter is KV Key value pair form,
        ServletConfig Objects can be K Key to get the corresponding value
        And this initialization parameter can have multiple groups-->
        <init-param>
            <!--param-name Is the parameter name-->
            <param-name>username</param-name>
            <!--param-value Is the parameter value-->
            <param-value>root</param-value>
        </init-param>
    </servlet>

Then let's take a look through the ServletConfig object:

@Override
    public void init(ServletConfig servletConfig) throws ServletException {
//        1. You can get the value of the alias Servlet name of the Servlet program
        System.out.println("HelloServlet The alias of the program is:"+servletConfig.getServletName());
//        2. You can get the initialization parameter init param
        System.out.println("HelloServlet Initialization parameters of the program username The values are:"+servletConfig.getInitParameter("username"));
//        3. You can get the ServletContext object
        System.out.println("HelloServlet programmatic ServletContext Object:"+servletConfig.getServletContext());

    }

be careful:
Each Servlet program will have a ServletConfig object. We can statically call the getServletConfig() method to get a ServletConfig object, but this ServletConfig object can only get the configuration information in this Servlet program, not in other Servlet programs.

For example, we call the getServletConfig method in HelloServlet2:

package com.atguigu.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//1. First, write a class to inherit the HttpServlet class, which is an implementation class of the Servlet interface
//Because HttpServlet is more convenient to use than Servlet interface
public class HelloServlet2 extends HttpServlet {

    //2. Rewrite the request method in HttpServlet
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doGet(req, resp); this can be removed and rewritten
        System.out.println("doGet method");
        //You can get the ServletConfig object directly
        ServletConfig servletConfig = getServletConfig();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doPost(req, resp); this can be removed and rewritten
        System.out.println("doPost method");
    }
}

There is another point to note:
For example, we now write the init method in HelloServlet2:

package com.atguigu.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//1. First, write a class to inherit the HttpServlet class, which is an implementation class of the Servlet interface
//Because HttpServlet is more convenient to use than Servlet interface
public class HelloServlet2 extends HttpServlet {

    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("Now we have to do something init Operation!");
//        super.init(config); override the provided code by default and reference the config of the parent class
        //Now let's annotate it. The null pointer exception will be reported where servletConfig is used below
        
    }

    //2. Rewrite the request method in HttpServlet
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doGet(req, resp); this can be removed and rewritten
        System.out.println("doGet method");
        ServletConfig servletConfig = getServletConfig();
        
        System.out.println("HelloServlet The alias of the program is:"+servletConfig.getServletName());
        System.out.println("HelloServlet Initialization parameters of the program username The values are:"+servletConfig.getInitParameter("username"));
        System.out.println("HelloServlet programmatic ServletContext Object:"+servletConfig.getServletContext());

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doPost(req, resp); this can be removed and rewritten
        System.out.println("doPost method");
    }
}

Now we will report null pointer exception when accessing:

So we must write the above commented code when we rewrite init:

super.init(config);

Why?

First of all, we should pay attention to where the getServletConfig is the instance object of the ServletConfig obtained.

You can see that this method is a method in GenericServlet.
As we said before, the GenericServlet class implements the Servlet interface, makes many empty implementations, holds a reference to the ServletConfig class, and makes some methods for the use of ServletConfig.


The config object is the constant defined in GenericServlet:

There is also an init method in this GenericService. This class saves the config object in this class in the init method:

Now let's look at the code just now:

@Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("Now we have to do something init Operation!");
//        super.init(config); override the provided code by default and reference the config of the parent class
        //Now let's annotate it. The null pointer exception will be reported where servletConfig is used below
        
    }

Both parent and child classes contain init methods. According to the knowledge of polymorphism, the init called by the object will only be the init method in our class HelloServlet2. When we just looked at the source code, we found it in GenericServlet (that is, our parent class) The operation of saving the config object in the class will be lost. Therefore, a null pointer exception will be reported when using the config object, so we must write super.init(config); this allows us to get the config object saved in the parent class.

ServletContext class

What is ServletContext?

1. ServletContext is an interface that represents a Servlet context object
2. A web project has only one ServletContext object instance.
3. The ServletContext object is a domain object.
4. ServletContext is created when the web project deployment starts. It is destroyed when the web project stops.

What is a domain object?

A domain object is an object that can access data like a Map. It is called a domain object. The domain here refers to the operation scope of accessing data and the whole web project.

Four functions of ServletContext class

1. Get the context parameter context param configured in web.xml
2. Get the current project path, format: / Project path
3. Get the absolute path on the server hard disk after project deployment
4. Access data like Map

Let's do this:
First create a ContextServlet class:

package com.atguigu.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ContextServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1. Get the context parameter context param configured in web.xml
        
//        2. Get the current project path, format: / Project path
//        3. Get the absolute path on the server hard disk after project deployment
//        4. Access data like Map
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}

Then let's set the following context parameters in web.xml:

<!--context-param Is a context parameter (it belongs to the whole web Project, and multiple groups can be configured)-->
    <context-param>
        <param-name>username</param-name>
        <param-value>context</param-value>
    </context-param>

Then we can call the getServletContext method through the getServletConfig method to get the context parameters:

package com.atguigu.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ContextServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1. Get the context parameter context param configured in web.xml
        ServletContext context = getServletConfig().getServletContext();
        String username = context.getInitParameter("username");
        System.out.println("context-param parameter username The values are:"+username);
//        2. Get the current project path, format: / Project path
        System.out.println("Current project path:"+context.getContextPath());
//        3. Get the absolute path on the server hard disk after project deployment
        /*
        The slash is resolved by the server to: http://ip:port/ Project name / web Directory mapped to IDEA code
         */
        System.out.println("Project deployment path:"+context.getRealPath("/"));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}

There is also a fourth function: ServletContext accesses data like a Map.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
	ServletContext context = getServletContext();
	System.out.println(context); 
	System.out.println("Context2 Get domain data from key1 The value of is:"+ context.getAttribute("key1")); 
}

Http protocol

What is the HTTP protocol

What is an agreement?
Agreement refers to the rules that both parties or multiple parties agree on and everyone needs to abide by. It is called agreement.
The so-called HTTP protocol refers to the rules that need to be observed for the data sent during the communication between the client and the server, which is called HTTP protocol.
Data in HTTP protocol is also called message.

HTTP protocol format of the request

The client sends a data request to the server.
The server sends back data to the client for response.
Requests are divided into GET requests and POST requests.

GET request


POST request


Description of common request headers

Accept: indicates the data type that the client can receive
Accpet language: indicates the language type that the client can receive
User agent: represents the information of the client browser
Host: indicates the server ip and port number at the time of the request

Which are GET requests and which are POST requests

What are the GET requests:
1. form tag method=get
2. a label
3. link tag introduces css
4. Script tag import js file
5. img tag import picture
6. iframe introduces html pages
7. Enter the address in the browser address bar and press enter

What are the POST requests:
1. form label method=post

The HTTP protocol format of the response


Description of common response codes

MIME type description

MIME is the data type in the HTTP protocol.
The full English name of mime is "Multipurpose Internet Mail Extensions" multifunctional Internet mail extension service. The format of MIME type is "large type / small type" and corresponds to the extension of a file.

Common MIME types:


How Google browser views the HTTP protocol:

Keywords: Java JavaEE servlet server

Added by Hellusius on Thu, 09 Dec 2021 13:32:23 +0200