Web Core-Http-Tomcat-Servlet Learning Record

Web: The global wide area network, also known as the World Wide Web (www), a web site that can be accessed through a browser

JavaWeb: It is a technology stack that uses Java technology to solve related web and Internet fields

Java Web technology stack

  • B/S architecture: Browser/Server, browser/server architecture mode, its characteristic is that the client only needs a browser, and the logic and data of the application are stored on the server. The browser only needs to request the server to obtain web resources, and the server sends the web resources to the browser.

    Benefits: Easy to maintain and upgrade: After the server is upgraded, the client can use the new version without any deployment

  • Static resources: HTML, CSS, JavaScript, images, etc. Responsible for page display

  • Dynamic resources: Servlets, JSPs, etc. Responsible for logic processing

  • Database: responsible for storing data

  • HTTP protocol: define communication rules

  • Web server: responsible for parsing the HTTP protocol, parsing request data, and sending response data

HTTP

Concept : HyperText Transfer Protocol, hypertext transfer protocol, specifies the rules for data transmission between browsers and servers

HTTP protocol features :

  • Based on TCP protocol: connection-oriented, safe
  • Based on the request-response model: a request corresponds to a response
  • The HTTP protocol is a stateless protocol: it has no memory for transaction processing. Each request-response is independent.
    • Disadvantage: Data cannot be shared between multiple requests. Use session technology (Cookie, Session) in Java to solve this problem
    • Advantages: fast

HTTP-request data format

The request data is divided into 3 parts :

  1. Request Line: The first line of the request data. Among them, GET indicates the request method, / indicates the request resource path, and HTTP/1.1 indicates the protocol version
  2. Request header: starting from the second line, the format is key: value.
  3. Request body: The last part of the POST request, storing request parameters

GET / HTTP/1.1

Host: www.itcast.cn

Connection: keep-alive

User-Agent: Mozilla/5.0 Chrome/91.0.4472.106

POST / HTTP/1.1

Host: www.itcast.cn

Connection: keep-alive

Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1

User-Agent: Mozilla/5.0 Chrome/91.0.4472.106

username=superbaby&password=123456

Difference between GET request and POST request :

  • GET request request parameters are in the request line, there is no request body.

    POST request request parameters in the request body

  • GET request request parameter size is limited,

    POST no

Common HTTP request headers :

  • Host: Indicates the requested host name
  • User-Agent: browser version, for example, the logo of Chrome browser is similar to Mozilla/5.0 ... Chrome/79, and the logo of IE browser is similar to Mozilla/5.0 (Windows NT ...) like Gecko;
  • Accept: Indicates the resource type that the browser can receive, such as text/*, image/ or /* means all;
  • Accept-Language: Indicates the language preferred by the browser, and the server can return web pages in different languages ​​accordingly;
  • Accept-Encoding: Indicates the compression type supported by the browser, such as gzip, deflate, etc.

HTTP-response data format

The response data is divided into 3 parts :

  • Response line: The first line of response data. Among them, HTTP/1.1 indicates the protocol version, 200 indicates the response status code, and OK indicates the status code description
  • Response header: starting from the second line, the format is key: value
  • Response body: the last part. store response data

HTTP/1.1 200 OK

Server: Tengine

Content-Type: text/html

Transfer-Encoding: chunked…

<html>

<head>

​ <title></title>

</head>

<body></body>

</html>

Common HTTP response headers :

  • Content-Type: Indicates the type of the response content, such as text/html, image/jpeg;
  • Content-Length: Indicates the length (number of bytes) of the response content;
  • Content-Encoding: Indicates the response compression algorithm, such as gzip;
  • Cache-Control: Indicates how the client should cache, for example max-age=300 means it can be cached for up to 300 seconds

Web server - Tomcat

web server

A web server is an application program (software) that encapsulates the operations of the HTTP protocol, so that programmers do not need to directly operate the protocol, making web development more convenient. The main function is to "provide online information browsing service".

Tomcat

Introduction

  • Concept: Tomcat is a core project of the Apache Software Foundation. It is an open source and free lightweight web server that supports a small number of JavaEE specifications for Servlet/ISP.
  • JavaEE: Java Enterprise Edition, Java Enterprise Edition. Refers to the sum of technical specifications for Java enterprise-level development. Contains 13 technical specifications: JDBC, JNDI, EJB, RMI, JSP, Servlet, XML, JMS, Java lDL, JTS, JTA, JavaMail, JAF
  • Tomcat is also known as Web container, Servlet container. Servlet needs to depend on Tomcat to run
  • Official website: https://tomcat.apache.org/

Basic usage: install, uninstall, start, shut down, configure, deploy projects

  • Download: official website download

  • Installation: Green version, just decompress it directly

  • Uninstall: Just delete the directory directly

  • Start: double-click: bin\startup.bat

    • The encoding of the Tomcat output log is UTF-8, while the encoding of the Windows console is GBK, and garbled characters generally appear.

      Modify conf/logging.properties

      java.util.logging.ConsoleHandler.encoding = GBK
      
  • closure:

    1. Directly × off the running window: forced to close
    2. bin\shutdown.bat: graceful shutdown
    3. Ctrl+C: normal shutdown
  • Configuration:

    Modify the startup port number: conf/server.xml

        <Connector port="8080" protocol="HTTP/1.1"
                   connectionTimeout="20000"
                   redirectPort="8443" />
    

    Note: The default port number of the HTTP protocol is 80. If you change the Tomcat port number to 80, you will not need to enter the port number when accessing Tomcat in the future.

  • Tomcat deployment project:

    Place the project in the webapps directory, and the deployment is complete

    Generally, JavaWeb projects will be packaged into a war package, and then put the war package in the webapps directory, and Tomcat will automatically decompress the war file

Create a Maven Web project in IDEA

Web project structure

Maven Web Project Structure: Projects in Development :

insert image description here

Deployed JavaWeb project structure: the project that can be deployed after development is completed:

  • The compiled Java bytecode files and resources resource files are placed in the classes directory under WEB-INF
  • The jar package corresponding to the dependent coordinates in pom.xml is placed in the lib directory under WEB-INF
Created using a skeleton

Skeleton: Project Templates

Create a new project or module, then click Maven Archetype and select in Archetype.

org.apache.maven.archetypes:maven-archetype-webapp

Click Create to complete the creation.

It can be found that there is no Java directory under main, right-click main, New, Directory, and directly select Java.

Not suitable for skeleton creation

Create a new project or module: File->New -> Module… or Project…

I create a module here, choose New Module, and choose Maven for Build System.

Click Create to complete the creation.

Then write the packaging method in pom.xml:

    <packaging>war</packaging>

Then to create the webapp directory, it can be created manually or automatically.

Automatic creation: Open Project Structure, select Facets, right-click Web, click Add, select Web, and select the project just created.

Modify the path in Deployment Descriptors.

Modify the path in Web Resource Directories.

Click Apply, and then click OK.

Using Tomcat in IDEA

There are two ways to integrate Tomcat in IDEA, namely integrating local Tomcat and Tomcat Maven plug-ins

Integrate local Tomcat

Click Edit Configurations..., then click the + sign, and select Tomcat Server, Local.

Click configure... after Application server, and select the path of Tomcat Home. Click OK.

Next is deployment, switch to Deployment. Click the + sign under Deploy at the server startup, then click Artifact..., and select tomcat-deom:war.

Finally, click apply, and then click OK to complete.

Tomcat Maven plugin

Add the Tomcat plug-in in pom.xml, you can use the shortcut key alt+(fn)+ins(ert)

  <build>
    <finalName>tomcat-deom</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
      </plugin>
    </plugins>
  </build>

In the project, right click ->Run Maven -> tomcat7:run to run

Maven Tomcat plug-in currently only has Tomcat7 version, no higher version can be used

Using the Maven Tomcat plug-in, if you want to modify the port and access path of Tomcat, you can directly modify pom.xml

  <build>
    <finalName>tomcat-deom</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <port>8000</port><!--访问端口号 -->
          <!--项目访问路径-->
          <path>/</path>
        </configuration>
      </plugin>
    </plugins>
  </build>

Servlet

Servlet is the core content of JavaWeb. It is a dynamic web resource development technology provided by Java.

Servlet is one of the JavaEE specifications, which is actually an interface. In the future, we need to define the Servlet class to implement the Servlet interface, and run the Servlet by the web server.

quick start

  1. Create a web project and import Servlet dependency coordinates

    	...
    
      <dependencies>
    
        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>4.0.1</version>
            <!--
          provided指的是在编译和测试过程中有效,最后生成的war包时不会加入
           因为Tomcat的lib目录中已经有servlet-api这个jar包,如果在生成war包的时候生效就会和Tomcat中的jar包冲突,导致报错
        -->
          <scope>provided</scope>
        </dependency>
    
      </dependencies>
    
      <build>
        <finalName>web-demo</finalName>
        <plugins>
          <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.2</version>
          </plugin>
        </plugins>
      </build>
    
    </project>
    
    
  2. Create: Define a class, implement the Servlet interface, rewrite all the methods in the interface, and output a sentence in the service method

    public class ServletDemo1 implements Servlet {
          
          
        public void init(ServletConfig servletConfig) throws ServletException {
          
          
    
        }
    
        public ServletConfig getServletConfig() {
          
          
            return null;
        }
    
        public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
          
          
            System.out.println("Servlet:Hello World!");
        }
    
        public String getServletInfo() {
          
          
            return null;
        }
    
        public void destroy() {
          
          
    
        }
    }
    
  3. Configuration: Use the @WebServlet annotation on the class to configure the access path of the Servlet

    @WebServlet("/demo1")
    public class ServletDemo1 implements Servlet {
          
          
        public void init(ServletConfig servletConfig) throws ServletException {
          
          
    
        }
    
        ...
    }
    
    
  4. Access: Start Tomcat, enter the URL in the browser to access the Servlet

Servlet execution process

  • The browser sends http://localhost:8080/web-demo/demo1a request, and three parts of the content can be parsed from the request, namely localhost:8080, web-demo,demo1
    • localhost:8080The Tomcat web server to access can be found according to
    • According to web-demothe web-demo project deployed on the Tomcat server can be found
    • According to demo1which Servlet class in the project can be found to be accessed, match according to the value behind @WebServlet
  • After finding the ServletDemo1 class, the Tomcat web server will create an object for the ServletDemo1 class , and then call the service method in the object
    • The service method has two parameters: ServletRequest and ServletResponse. ServletRequest encapsulates the request data, and ServletResponse encapsulates the response data.

Servlet life cycle

Life cycle: The life cycle of an object refers to the entire process of an object from being created to being destroyed.

Servlet runs in the Servlet container (web server), and its life cycle is managed by the container, which is divided into 4 stages:

  1. Loading and instantiation : By default, when the Servlet is accessed for the first time, the Servlet object is created by the container

    By default, Servlets are created by the container on first access.

    It is also possible to create a Servlet when the server starts:

    /*
    loadOnstartup的取值有两类情况
    	(1)负整数:第一次访问时创建Servlet对象
    	(2)0或正整数:服务器启动时创建Servlet对象,数字越小优先级越高
    */
    @WebServlet(urlPatterns = "/demo1",loadOnStartup = 1)
    
  2. Initialization : After the Servlet is instantiated, the container will call the Servlet's init() method to initialize the object, and complete some initialization tasks such as loading configuration files and creating connections. This method is called only once

  3. Request processing : Every time a Servlet is requested, the Servlet container will call the Servlet's service() method to process the request

  4. Service termination : When the memory needs to be released or the container is closed, the container will call the destroy() method of the Servlet instance to complete the release of resources. After the destroy() method is called, the container will release the Servlet instance, which will then be recycled by Java's garbage collector

In the Terminal command line, you can use mvn tomcat7:runthe startup, and then use ctrl+cthe shutdown tomcat

package com.xlr.web;

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

@WebServlet(urlPatterns = "/demo2",loadOnStartup = 1)
public class ServletDemo2 implements Servlet {
    
    

    /**
     *  初始化方法
     *  1.调用时机:默认情况下,Servlet被第一次访问时,调用
     *      * loadOnStartup: 默认为-1,修改为0或者正整数,则会在服务器启动的时候,调用
     *  2.调用次数: 1次
     */
    public void init(ServletConfig servletConfig) throws ServletException {
    
    
        System.out.println("init...");
    }

    public ServletConfig getServletConfig() {
    
    
        return null;
    }

    /**
     * 提供服务
     * 1.调用时机:每一次Servlet被访问时,调用
     * 2.调用次数: 多次
     */
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
    
    
        System.out.println("Servlet:Hello World!");
    }

    public String getServletInfo() {
    
    
        return null;
    }

    /**
     * 销毁方法
     * 1.调用时机:内存释放或者服务器关闭的时候,Servlet对象会被销毁,调用
     * 2.调用次数: 1次
     */
    public void destroy() {
    
    
        System.out.println("destroy");
    }
}

Servlet method

  • Initialization method, executed when the Servlet is created, only executed once
void init(ServletConfig servletConfig)
  • Provide a service method, which will be called every time the Servlet is accessed
void service(ServletRequest servletRequest, ServletResponse servletResponse)
  • Destroy method, when the Servlet is destroyed, this method is called. Destroy Servlet on memory deallocation or server shutdown
void destroy() 

The remaining two methods are:

  • Get Servlet information
String getServletInfo() 
//该方法用来返回Servlet的相关信息,没有什么太大的用处,一般我们返回一个空字符串即可
public String getServletInfo() {
    
    
    return "";
}
  • Get the ServletConfig object
ServletConfig getServletConfig()

Servlet Architecture

image description

We will develop web projects with B/S architecture in the future, all for the HTTP protocol, so we will customize the Servlet by inheriting HttpServlet

@WebServlet("/demo4")
public class ServletDemo4 extends HttpServlet {
    
    

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //TODO GET 请求方式处理逻辑
        System.out.println("get");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //TODO POST 请求方式处理逻辑
        System.out.println("post");
    }
}
  • If you want to send a GET request to request the Servlet, you only need to send it through the browser http://localhost:8080/web-demo/demo4, and you can see that the doGet method is executed

  • To send a POST request , you need to write a form form to send the request, and create a a.htmlpage under webapp with the following content:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
    <form action="/web-demo/demo4" method="post">
      <input name="username"><input type="submit">
    </form>
    
    </body>
    </html>
    

    Start the test and you can see that the doPost method is executed.

When the front end sends GET and POST requests, the positions of the parameters are inconsistent. The GET request parameters are in the request line, and the POST request parameters are in the request body. In order to handle different request methods, we have to make judgments in the service method, and then write different business processing.

@WebServlet(urlPatterns = "/demo5",loadOnStartup = 1)
public class ServletDemo5 implements Servlet {
    
    

    public void init(ServletConfig servletConfig) throws ServletException {
    
    
        System.out.println("init...");
    }

    public ServletConfig getServletConfig() {
    
    
        return null;
    }

    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
    
    
        //获取请求方式,根据不同的请求方式进行不同的业务处理
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        //1. 获取请求方式
        String method = request.getMethod();

        //2. 判断
        if ("GET".equals(method)) {
    
    
            // get方式处理逻辑
        } else if ("POST".equals(method)) {
    
    
            // get方式处理逻辑
        }

    }

    public String getServletInfo() {
    
    
        return null;
    }

    public void destroy() {
    
    
        System.out.println("destroy");
    }
}

We can inherit and encapsulate the Servlet interface to simplify code development.

package com.xlr.web;

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

public class MyHttpServlet implements Servlet {
    
    
    public void init(ServletConfig servletConfig) throws ServletException {
    
    

    }

    public ServletConfig getServletConfig() {
    
    
        return null;
    }

    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
    
    
        //获取请求方式,根据不同的请求方式进行不同的业务处理
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        //1. 获取请求方式
        String method = request.getMethod();

        //2. 判断
        if ("GET".equals(method)) {
    
    
            // get方式处理逻辑
            doGet(request,servletResponse);
        } else if ("POST".equals(method)) {
    
    
            // get方式处理逻辑
            doPost(request,servletResponse);
        }
    }

    protected void doPost(ServletRequest req, ServletResponse res) {
    
    
    }

    protected void doGet(ServletRequest req, ServletResponse res) {
    
    
    }

    public String getServletInfo() {
    
    
        return null;
    }

    public void destroy() {
    
    

    }
}

With the MyHttpServlet class, when we write the Servlet class in the future, we only need to inherit MyHttpServlet and rewrite the doGet and doPost methods in the parent class to process the business logic of GET and POST requests.

package com.xlr.web;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;

@WebServlet("/demo")
public class ServletDemo extends MyHttpServlet{
    
    

    @Override
    protected void doPost(ServletRequest req, ServletResponse res) {
    
    
        System.out.println("post...");
    }

    @Override
    protected void doGet(ServletRequest req, ServletResponse res) {
    
    
        System.out.println("get...");
    }
}

Servlet urlPattern placement

To be accessed, the Servlet must configure its access path (urlPattern)

A Servlet can be configured with multiple urlPatterns

@WebServlet(urlPatterns = {
    
    "/demo","/demo0"})

urlPattern configuration rules:

  1. exact match

    • Configuration path:@WebServlet("/demo5")
    • Access path:localhost:8030/web-demo/demo5
  2. directory match

    • Configuration path:@WebServlet("/demo/*")

    • Access path:

      localhost:8030/web-demo/demo
      localhost:8030/web-demo/demo/abc
      localhost:8030/web-demo/demo/123
      localhost:8030/web-demo/demo/abc/123
      

      /*Represents zero or more levels of access to the directory, and the priority of exact matching is higher than that of directory matching.

  3. extension match

    • Configuration path:@WebServlet("*.do")
    • Access path:
    localhost:8030/web-demo/abc.do
    localhost:8030/web-demo/123.do
    
    1. If the path configuration is not an extension, then it must be added in front of the path /, otherwise an error will be reported
    2. If the path configuration is *.do, then it cannot be added in front of *.do /, otherwise an error will be reported
  4. any match

    • Configuration path:

      @WebServlet("/")
      @WebServlet("/*")	
      
    • Access path:

      localhost:8030/web-demo/abc
      localhost:8030/web-demo/123
      

      When the Servlet in our project is configured with "/", it will overwrite the DefaultServlet in tomcat

      It will cause a custom Servlet class instead of the default one when requesting static resources, such as: localhost:8030/web-demo/a.html cannot be accessed

      **DefaultServlet:** Use this Servlet when other url-patterns do not match

    The priority is exact match > directory match > extension match > /* > /

Write Servlet in XML configuration mode

Servlet supports annotation configuration since version 3.0, and only supports the configuration method of XML configuration files before version 3.0.

There are two steps for XML configuration steps:

  • Write Servlet class

  • Configure the Servlet in web.xml

    <web-app>
      <display-name>Archetype Created Web Application</display-name>
    
      <!--Servleet全类名-->
      <servlet>
        <servlet-name>demo</servlet-name>
        <servlet-class>com.xlr.web.ServletDemo</servlet-class>
      </servlet>
    
      <!--Servlet访问路径-->
      <servlet-mapping>
        <!-- servlet的名称,要和上面的名称一致-->
        <servlet-name>demo</servlet-name>
        <url-pattern>/demo</url-pattern>
      </servlet-mapping>
    
    </web-app>
    

Guess you like

Origin blog.csdn.net/m0_61465701/article/details/129644441