[java learning path] (javaWeb [back end] Chapter) 002 Servlet

Posted by ProblemHelpPlease on Mon, 28 Feb 2022 01:35:14 +0100

Chapter 1 Introduction to Servlet

1. Learning objectives

  • Understanding Web resources

  • Understand the concept of Servlet

  • Master the function of Servlet

  • Master the XML configuration of Servlet

  • Understand the annotation mode configuration of Servlet

2. Content explanation

2.1 concept of web resources

Web resources are resources running on the server. They are divided into two categories: static resources and dynamic resources

2.1.1 static resources

Static resources are the data for people to browse in the web page, which is always the same. For example, the html, css, js, pictures, audio and video we learned before belong to static resources

2.1.2 dynamic resources

Dynamic resources are the data for people to browse in the web page, which are generated by the program. Different users or different time points visit the web page to see different contents. For example, Servlet, JSP (not learn), Thymeleaf and so on are dynamic resources

2.2 concept of Servlet

2.2.1 what is a Servlet

Servlet is a Java applet running on the server (tomcat), which is a set of dynamic resource specification provided by sun company; From the code level, servlet is an interface

2.2.2 function of Servlet

Dynamic resources used to receive and process client requests and respond to browsers. In the whole Web application, Servlet is mainly responsible for processing requests and coordinating scheduling functions. We can call servlets "controllers" in Web applications

2.2.2 function diagram of Servlet

Effect to be achieved

Specific details of using Servlet implementation

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-yql0iudj-16460077772417)( https://gitee.com/bwcx_fdsz/cloudimage/raw/master/img/202202271454956.png )]

2.3 introduction case of Servlet

2.3.1 objectives

Click the hyperlink on the page, and the Servlet will process the request and return a response string: Hello,I am Servlet

2.3.2 ideas

2.3.3 implementation steps
Step 1: create a dynamic Web module
Step 2: create an html page
<!-- /Web Application address/Servlet address -->
<a href="/app/helloServlet">Servlet Hello World</a>
Step 3: create HelloServlet class
public class HelloServlet 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 {

        // Print on the console to prove that this method has been called
        System.out.println("I am HelloServlet,I did it!");

        // Return response string
        // 1. Gets a character stream object that can return response data
        PrintWriter writer = servletResponse.getWriter();

        // 2. Write data to character stream object
        writer.write("Hello,I am Servlet");
    }

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

    @Override
    public void destroy() {

    }
}
Step 4: on the web Configure HelloServlet in XML

Location of configuration file: WEB-INF / Web xml

<!-- to configure Servlet itself -->
<servlet>
    <!-- The full class name is too long. Here you are Servlet Set a short name -->
    <servlet-name>HelloServlet</servlet-name>

    <!-- to configure Servlet Full class name of -->
    <servlet-class>com.atguigu.servlet.HelloServlet</servlet-class>
</servlet>

<!-- take Servlet Associated with access address -->
<servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/helloServlet</url-pattern>
</servlet-mapping>

Mapping path: Servlet is not a directory or file that actually exists in the file system. Therefore, in order to facilitate browser access, we created a mapping path to access it.

2.3.4 summary

Requirements: you can access Java programs by clicking hyperlinks on the browser

2.4 concept sorting

Native Tomcat

Real Tomcat software installed on the computer

2.4.2 Tomcat instance in idea

The Tomcat instance integrated on the idea through the configuration of the idea actually uses the native Tomcat software

2.4.3 Web Engineering in idea

The dynamic Web project written by programmers using IDEA is only used for programmer coding. In fact, this project is not deployed and run in Tomcat server

2.4.4 war package generated according to Web project

According to the dynamic Web project created by the programmer, the IDEA will package it into a war package, while the war package is actually deployed and run in the Tomcat server

2.4.5 address to access resources
2.4.5.1 accessing static resources

/Web application name / path of static resource itself

2.4.5.2 accessing dynamic resources

/Web app name / mapping path

2.4.6 Web application name

Note that the Web application name is not the name of your project or Module, but the content of your ApplicationContext during deployment

2.4.7 overall logical structure

2.5 annotation mode configuration of servlet (just understand)

Note: a Servlet can be configured either by configuration file or by annotation. You can't use both

Advantages of using annotation configuration: simpler code

Disadvantages of using annotation configuration: high coupling

We generally prefer to use the configuration file method to configure the Servlet, especially the Servlet in the third-party framework: for example, the dispatcher Servlet in spring MVC can only be configured using the configuration file method

2.5.1 code implementation using annotation configuration
In the to be configured Servlet Class@WebServlet("/Mapping path")

Chapter 2 advanced design of Servlet

1. Learning objectives

  • Master the life cycle and life cycle method of Servlet
  • Master the use of ServletConfig
  • Master the architecture of Servlet
  • Master the way to write the mapping path of Servlet
  • Master the most common methods of creating servlets

2. Content explanation

2.1 Servlet life cycle and life cycle method

2.1.1 what is the life cycle of a Servlet

The life cycle of servlet is the process from creation to destruction of servlet. What we want to discuss is when the servlet object is created and destroyed. Of course, we don't need to do the work of creating and destroying servlet objects

2.1.2 when is the servlet object created

By default, the Servlet object is created the first time there is a request to access the Servlet instance

2.1.3 when will servlet objects be destroyed

All Servlet objects in the current project will be destroyed when the server is shut down or the current project is removed from the server

2.2 Servlet life cycle method

2.2.1 what is the lifecycle approach of servlets

The methods that must be experienced in the life cycle of a Servlet are called the life cycle method of a Servlet. There are three methods in total: init, service and destroy

2.2.2 init method

This method will be executed after the Servlet instance object is created. In this method, we can obtain the initialization parameters of the current Servlet and perform some operations such as reading the configuration file

2.2.3 service method

This method will be executed every time the Servlet instance object receives a request. In this method, we can receive and process the request and respond the data required by the client to the client

2.2.4 destroy method

This method will be executed before the Servlet instance object is destroyed. We can do some operations in this method, such as resource recycling, releasing, closing and so on

2.3 configure Servlet creation in advance

Sometimes we need to do some time-consuming operations such as resource loading when the Servlet is created. Therefore, if the Servlet is created when the request is received for the first time, it will inevitably affect the user's access speed. Therefore, at this time, we need to create the Servlet in advance and advance the creation of the Servlet until the server starts.

By modifying the web The Servlet configuration in XML can realize:

<!-- to configure Servlet itself -->
<servlet>
    <!-- The full class name is too long. Here you are Servlet Set a short name -->
    <servlet-name>HelloServlet</servlet-name>

    <!-- to configure Servlet Full class name of -->
    <servlet-class>com.atguigu.servlet.HelloServlet</servlet-class>

    <!-- to configure Servlet Start sequence -->
    <load-on-startup>1</load-on-startup>
</servlet>

2.4 introduction to ServletConfig

2.4.1 Interface Overview

Interface method introduction
Method nameeffect
getServletName()Get the Servlet name defined by < Servlet name > helloservlet < / Servlet name >
getServletContext()Get ServletContext object
getInitParameter()Get the initialization parameters set when configuring the Servlet, and get the value according to the name
getInitParameterNames()Gets the Enumeration object composed of all initialization parameter names
2.4.3 get initialization parameters of Servlet

We can do it on the web Configure initialization parameters for Servlet in XML. Next, you can get the value of the configured initialization parameters in the init method of Servlet

web.xml code

<!-- to configure Servlet itself -->
<servlet>
    <!-- The full class name is too long. Here you are Servlet Set a short name -->
    <servlet-name>HelloServlet</servlet-name>

    <!-- to configure Servlet Full class name of -->
    <servlet-class>com.atguigu.servlet.HelloServlet</servlet-class>

    <!-- Configure initialization parameters -->
    <init-param>
        <param-name>goodMan</param-name>
        <param-value>me</param-value>
    </init-param>

    <!-- to configure Servlet Start sequence -->
    <load-on-startup>1</load-on-startup>
</servlet>

HelloServlet code

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

        System.out.println("HelloServlet Object initialization");

        // Test the use of ServletConfig object
        // 1. Get ServletConfig object: complete in init() method
        System.out.println("servletConfig = " + servletConfig.getClass().getName());

        // 2. Get initialization parameters through servletConfig object
        Enumeration<String> enumeration = this.servletConfig.getInitParameterNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            System.out.println("name = " + name);

            String value = this.servletConfig.getInitParameter(name);
            System.out.println("value = " + value);
        }

    }

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

        // Print on the console to prove that this method has been called
        System.out.println("I am HelloServlet,I did it!");

        // Return response string
        // 1. Gets a character stream object that can return response data
        PrintWriter writer = servletResponse.getWriter();

        // 2. Write data to character stream object
        writer.write("Hello,I am Servlet");
    }

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

    @Override
    public void destroy() {
        System.out.println("HelloServlet The object is about to be destroyed. Now perform the cleanup operation");
    }
}

2.5 Servlet architecture (understand)

2.5.1 type relationship

An implementation class of the Servlet interface is GenericServlet, while a subclass of GenericServlet is HttpServlet. When we create a Servlet, we will choose to inherit HttpServlet, because it also implements the Servlet interface, and makes default implementation for some methods; Moreover, the function of the subclass will be more powerful than that of the parent class

2.5.2 method relationship

When we write a Servlet class to inherit HttpServlet, we only need to rewrite the doGet() and doPost() methods, because HttpServlet rewrites the service() method, judges the request mode in the service() method, and executes the doXXX() method according to different request modes

2.6 create servlets directly using Idea

2.6.1 creation steps

2.6.2 code after creation

web.xml code

<!-- IDEA Automatically generated servlet label -->
<servlet>
    <servlet-name>QuickServlet</servlet-name>
    <servlet-class>com.atguigu.servlet.QuickServlet</servlet-class>
</servlet>

<!-- We'll add it ourselves servlet-mapping label -->
<servlet-mapping>
    <servlet-name>QuickServlet</servlet-name>
    <url-pattern>/QuickServlet</url-pattern>
</servlet-mapping>

Servlet code

public class QuickServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //In the doPost() method, doGet() is called, so it only needs to rewrite the doGet() method to handle post and get requests.
		doGet(request,response);
    }

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

2.7 configuration of three mapping paths of Servlet

2.7.1 function of mapping path

The mapping path of a Servlet is to provide a path for others to access the Servlet. For example, if the mapping path of a Servlet is "/ hello", then the path to access the Servlet on the browser is http://localhost:8080/ Signature of project department / hello

Note: a Servlet can be configured with multiple mapping paths, but multiple servlets cannot be configured with the same mapping path

2.7.2 classification of mapping paths
2.7.2.1 complete path matching

The path to access the current Servlet must be exactly the same as the configured mapping path. For example, if the Servlet configuration is / demo01, the path to access the Servlet must also be http://localhost:8080/ Only when the project department signs / demo01 can it be accessed

2.7.2.2 directory matching

Start with / and end with *. Note: not much is used in servlets, but directory matching is usually used in filters

for example:  to configure/* The access path can be written as/Arbitrary string,example: /aa, /aaa; to configure /aa/*  The access path can be written as/aa/Arbitrary string,example: /aa/b , /aa/cc
2.7.2.3 extension matching

Start with * and start with The extension ends and can match all Request path at the end of the same extension

for example:  *.action;  The access path can be any string.action,example: aa.action, bb.action, c.action;

The third chapter is the path of dynamic Web engineering

1. Learning objectives

  • Master the comparison between development project directory structure and deployment project directory structure
  • Master url
  • Master uri
  • Master the writing method of relative path
  • Master the writing of absolute path
  • Master the dynamic access context path

2. Content explanation

2.1 why write path

  • The whole system should be divided into many independent resources according to functions
  • Resources should not only complete their own functions, but also cooperate with other resources
  • The write path is to jump from one resource to the next

2.2 structure comparison between project directory and deployment directory

2.2.1 project catalogue

Where we write code, but this is not what runs on the server

2.2.2 deployment directory

After Java source file compilation and directory reorganization, IDEA prepares the deployment directory that can run on the server for us

2.2.3 benchmark of writing path

Users access the server through the browser, and the deployment directory is running on the server, so when writing the path, refer to the deployment directory instead of the project directory

2.2.4 correspondence between project directory and deployment directory

The web directory under the project directory corresponds to the root directory of the deployment directory, and the root directory of the deployment directory is also the web application root directory in the path

2.3 introduction to URL

2.3.1 concept of URL

url is the abbreviation of uniform resource locator, which is translated into uniform resource locator in Chinese. It is the only access address of an Internet resource, and the client can access specific Internet resources through url

2.3.2 composition of URL

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-xKfZk8xj-1646007772420)(images/img027.png)]

2.3.3 usage scenario of URL

The client accesses the resources of the server, or the resources of one server to access another server are accessed through url

2.4 introduction of URI

2.4.1 concept of URI

uri is the abbreviation of Uniform Resource identifier, which is translated into Uniform Resource identifier in Chinese. It is the unique identification of a resource in the server. Through uri, one resource in the same project can access another resource

2.4.2 composition of URI

uri is written as / signature of the project department / resource path

2.4.3 usage scenarios of URI

Access another resource in the same project from one resource in the same project

2.5 use of relative path (not recommended)

2.5.1 objectives

Objective: access B resource in A resource

A uri path of resource: / app/pages/a.html

B resource uri path: / APP / static / Vue js

2.5.2 concept of relative path

Relative path is a path writing method that does not start with /. The principle of writing relative path is to use the uri path of the target resource relative to the uri path of the current resource

2.5.3 relative path examples

Then the relative path to access B resources in A resource is written as/ static/vue.js, where/ Static means to find the static directory under the upper directory of the current resource

2.6 use of absolute path (recommended)

2.6.1 objectives

Objective: access B resource in A resource

A uri path of resource: / app/pages/a.html

B resource uri path: / APP / static / Vue js

2.6.2 concept of absolute path

Absolute path is the path writing method starting with /. The principle of writing absolute path is to access the target resource through the uri of the target resource, but the special case is to request forwarding. If it is to request forwarding to access the target resource, the absolute path omits / Project signature on the basis of uri

2.6.3 absolute path example

The absolute path to access B resources in A resource is written as / APP / static / Vue js

2.6.3 use absolute path when requesting forwarding

Request forwarding will be explained in the following content. Now we only need to understand that when requesting forwarding, the writing method of absolute path is / resource name, which is actually omitting / signature of project department on the basis of uri

2.7 get context path dynamically

2.7.1 concept of context path

context path = / Web application name

2.7.2 why dynamically obtain context path

Because we need to use the uri path of the resource when using the absolute path, and the uri path contains the context path, if we write the absolute path in a static way, the context path will be written in the absolute path; When we deploy the project, the context path is variable, so this will lead to the problem of absolute path error because the context paths set during deployment are different

2.7.3 API for dynamically obtaining context path
request.getContextPath()

Using the above API, you can dynamically obtain the context path of the project, and each time you obtain the value of the actual context path in the current environment

Chapter 4 ServletContext

1. Learning objectives

  • Master the concept of ServletContext
  • Master how to get ServletContext object in Servlet
  • Master ServletContext to obtain global initialization parameters
  • Master ServletContext as a global domain object
  • Master ServletContext and get the real path

2. Content explanation

2.1 concept of ServletContext

The server creates a ServletContext object for each application (project) it deploys. ServletContext belongs to the whole project. All servlets in the project can share the same ServletContext object

2.2 API for obtaining ServletContext

2.2.1 call the getServletContext method of the Servlet itself to obtain
ServletContext ServletContext = getServletContext()
2.2.2 call getServletContext method of ServletConfig interface
ServletContext ServletContext = servletConfig.getServletContext();
//The HttpServletRequest object also implements the ServletConfig interface, so there is also a getServletContext() method
ServletContext ServletContext = request.getServletContext();

2.3 ServletContext obtaining global initialization parameters

2.3.1 on the Web Configure initialization parameters of Web application level in XML
<context-param>
    <param-name>username</param-name>
    <param-value>hahahaha</param-value>
</context-param>
2.3.2 get global parameters in the doGet method of Servlet
String username = servletContext.getInitParameter("username");
System.out.println("stay ServletDemo04 Get global initialization parameters from username=" + username);

2.4 ServletContext as a global domain object

2.4.1 what are domain objects

Domain objects are objects that share data within a certain scope. As a global domain object, ServletContext can share data in all dynamic resources (including all servlets) of the whole project

2.4.2 API of ServletContext as domain object
2.4.2.1 storing data into local objects
servletContext.setAttribute("key",value)
2.4.2.2 take out data from local objects
Object value = ServletContext.getAttribute("key");
2.4.3 cases
2.4.3.1 objectives

In ServletDemo01, store the key value pair with "username" as "aobama" into the global object, and then obtain the corresponding value from the global object according to "username" in ServletDemo02

2.4.3.2 code

Code in ServletDemo01

//1. Get ServletContext object
ServletContext ServletContext = getServletContext();
//2. Data storage
servletContext.setAttribute("username","aobama");

Code in ServletDemo02

//1. Get ServletContext object
ServletContext ServletContext = getServletContext();
//2. Take out data
String username = (String)servletContext.getAttribute("username");
//3. Print data
System.out.println(username)

2.5 real path to obtain resources

2.5.1 why do you need to use code to obtain the real path of resources

For example, our goal is to obtain the path of a static resource in the project, not the path in the project directory, but the path in the deployment directory; If we directly copy the complete path in our computer, there is a problem, because if the project is deployed to the company server in the future, the path will certainly change, so we need to use code to dynamically obtain the real path of resources

2.5.2 API for obtaining the real path of resources
String realPath = servletContext.getRealPath("Resources in web Path in directory");
2.5.3 advantages of dynamic access to real paths

As long as the servletContext is used to dynamically obtain the real path of resources, no matter what happens to the deployment path of the project, the actual path at the time of project operation will be dynamically obtained. Therefore, the path error caused by the change of project deployment location due to the writing of the real path will not occur

Topics: Java Back-end