Servlet core technology

Posted by Skoalbasher on Fri, 03 Dec 2021 09:08:03 +0100

Chapter 1 Servlet core technology (Part I)

1.1 basic concepts (common sense)

1.1.1 concept of C / S architecture

  • C/S architecture (Client/Server, Client/Server mode) is an early software architecture and a very common structure in life. This structure reasonably allocates the business to be processed to the client and server. The client is usually responsible for completing the interaction tasks with users, and the server is usually responsible for data management.
  • The main advantages of C/S architecture are as follows:
    • The interface and functions of the client can be very rich.
    • The load of the application server is light.
    • Fast response.
  • The main disadvantages of C/S architecture are as follows:
    • Narrow application area and fixed user group.
    • The cost of maintenance and upgrade is high, and all clients need to be updated.

1.1.2 concept of B / S architecture

  • B/S architecture (Browser/Server, Browser/Server mode) is a software architecture after the rise of the Internet. This structure centralizes the main business logic of the system function implementation to the server, and a few business logic are implemented in the browser. The browser is usually responsible for completing the interaction tasks with users, and the server is usually responsible for data management.
  • The main advantages of B/S architecture are as follows:
    • There is no need to install the client, as long as there is a browser.
    • It is widely applicable and the user group is not fixed.
    • The purpose of multi client access is realized through permission control, which has strong interaction.
    • The cost of maintenance and upgrade is low, and there is no need to update all client versions.
  • The main disadvantages of B/S architecture are as follows:
    • The application server is heavily loaded.
    • The interface and functions of the browser need to spend a lot of cost to achieve the richness of the client.
    • It is not satisfactory on cross browser, and the adaptation is troublesome.

1.1.3 concept of Java Web

  • Web originally means web page, which means resources on the Internet for external access.
  • Resources on the Internet for external access are mainly divided into the following two types:
    • Static resources: it mainly refers to that the data for people to browse in the Web page is always unchanged.
    • Dynamic resources: it mainly refers to the data for people to browse in the Web page, which is generated by the program, and the content seen when visiting the page at different time points is different.
  • JavaWeb mainly refers to the general term of dynamic Web resource development technology using Java language. It is the sum of technologies to solve the related Web and Internet fields.
  • Early B/S architecture
    •  
  • Later B/S architecture

1.2 HTTP protocol (familiar)

1.2.1 concept of HTTP protocol

  • HTTP protocol (HyperText Transfer Protocol) is an application layer protocol formulated by W3C (World Wide Web Consortium). It is used to standardize the data format of how to communicate between browser and web server, mainly involving the request format of browser and the response format of server.
  • HTTP protocol is usually hosted on TCP protocol, and the protocol hosted on TLS or SSL protocol layer is often referred to as HTTPS protocol.
  • The default port number of HTTP is 80 and that of HTTPS is 443.

1.2.2 HTTP request format

  • The request message that the client sends an HTTP request to the server mainly includes: request line, request header, blank line and request body.
    • The request line is used to describe the type of request, the resources to be accessed, and the resources to be used HTTP Version in the following format:
          The version of the path protocol requested by the request type(1.1)
      The request header is the part immediately after the request line (i.e. the first line), which is used to describe the additional information to be used by the server, including the format( key:value)As follows:
          Browser related information of host request length request
       A blank line is an empty line in the request header. Even if the subsequent request data is empty, there must be an empty line.
      
      The request body is also called request data, and any other data can be added.
  • Examples are as follows:
    • POST /task01_demo01/demo1.html HTTP/1.1
      Host: localhost:8088
      Content-Length: 21
      Cache-Control: max-age=0
      User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64)
      name=scott&pwd=123456

1.2.3 HTTP response format

  • Generally, the server will return an HTTP response message after receiving and processing the request sent by the client, mainly including response line, response header, blank line and response body.
    • The response line is used to describe HTTP Protocol version number, status code and status message in the following format:
          Version of the agreement(1.0 1.1) Status code (200 Success 404 path error 500 service error) The status information response header is used to describe some additional information to be used by the client, including the format( key:value). 
      A blank line is an empty line in the response header. Even if the subsequent request data is empty, there must be an empty line.
      
      The response body is used to the text information returned by the server to the client.
  • Examples are as follows:
  • HTTP/1.1 200 OK
    Content-Type: text/html
    Content-Length: 588
    Date: Thu, 08 Sep 2021 12:59:54 GMT
    
    <html>
        <head>
            <title>Example 1</title>
        </head>
        <body>
            <h1>This is a HTML page</h1>
        </body>
    </html>    

1.3 Tomcat server (key)

1.3.1 basic concepts

  • Tomcat was originally meant to be a public cat. It was originally developed by James Duncan Davidson, a software architect of Sun company. Later, he helped turn it into an open source project and contributed it to the Apache Software Foundation by Sun company.
  • Tomcat server is an open source lightweight Web application server, which is widely used in small and medium-sized systems and occasions with small concurrency. It is the first choice for developing and debugging Servlet and JSP programs.

1.3.2 installation method

  • Download address: http://tomcat.apache.org/

1.3.3 directory structure

  • bin mainly stores binary executable files and scripts.
  • conf mainly stores various configuration files.
  • lib is mainly used to store the jar packages that need to be loaded for Tomcat operation.
  • logs mainly stores the log files generated during the operation of Tomcat.
  • temp mainly stores temporary files generated by Tomcat during operation.
  • webapps mainly stores applications. When Tomcat starts, it will load the applications in this directory.
  • work mainly stores the compiled files of tomcat at run time, such as JSP compiled files.

1.3.4 startup and shutdown

  • Start mode
    • Use the batch file startup.bat in the bin directory to start the Tomcat server. If a millisecond occurs, it indicates that the startup is successful.
  • Closing mode
    • Use the batch file shutdown.bat in the bin directory to shut down the Tomcat server.
  • matters needing attention
    • Before starting, first install JDK and configure the environment variable JAVA_HOME. If you want the Tomcat server to start in any path, you need to configure the environment variable CATALINA_HOME.
    • Processing method of startup information garbled Code: modify the logging.properties file to java.util.logging.ConsoleHandler.encoding = GBK

1.3.5 configuration file

  • The server.xml file is the main configuration file of the server. You can set the port number, domain name or IP, default loaded items, request code, etc.
    • <Connector port="8888" protocol="HTTP/1.1"
                    connectionTimeout="20000"
                    redirectPort="8443" />
  • The tomcat-users.xml file is used to configure and manage the users and permissions of the Tomcat server.
    • <role rolename="manager-gui"/>
      <user username="admin" password="123456" roles="manager-gui"/>

1.4 concept and use of servlet (key points)

1.4.1 basic concepts

  • Servlet (Server Applet) is the abbreviation of Java Servlet, called small service program or service connector. It is a server-side program written in Java language. In other words, servlet is a Java class running on the server.
  • Servlet is used to complete the response processing of client requests under B/S architecture, that is, interactively browse and generate data and generate dynamic Web content.

1.4.2 programming steps of Servlet

  • Build a Java Web Application project and configure the Tomcat server.
  • The custom class implements the Servlet interface or inherits the HttpServlet class (recommended) and overrides the service method.
  • Configure the information of the custom class into the web.xml file and start the project. The configuration method is as follows:

 

<!-- to configure Servlet -->
<servlet>
  <!-- HelloServlet yes Servlet Alias of class -->
  <servlet-name> HelloServlet </servlet-name>
  <!-- com.lagou.task01.HelloServlet Is the real that contains the path Servlet Class name -->
  <servlet-class> com.lagou.task01.HelloServlet </servlet-class>
</servlet>
<!-- mapping Servlet -->
<servlet-mapping>
  <!-- HelloServlet yes Servlet The alias of the class must be the same as the above name -->
  <servlet-name> HelloServlet </servlet-name>
  <!-- /hello Is the address for the browser -->
  <url-pattern> /hello </url-pattern>
</servlet-mapping>

 

  • Access on the browser:
  • http://localhost:8080 / contents of project path / url pattern

1.4.3 Servlet interface

(1) Basic concepts

  • The javax.servlet.Servlet interface is used to define the methods that all servlets must implement.

(2) Common methods

1.4.5 GenericServlet class

(1) Basic concepts

  • javax.servlet.GenericServlet class is mainly used to define a general and protocol independent servlet, which implements the servlet interface.
  • If you write a general servlet, you only need to rewrite the service abstract method.

(2) Common methods

1.4.6 HttpServlet class

(1) Basic concepts

  • The javax.servlet.http.HttpServlet class is an abstract class and inherits the GenericServlet class.
  • Used to create an HTTP Servlet for a web site. Subclasses of this class must override at least one method.

(2) Common methods

1.4.7 Servlet life cycle

 

 

 

  • The constructor is called only once. When the Servlet is requested for the first time, the constructor is called to create an instance of the Servlet.
  • The init method is called only once. When the Servlet instance is created, this method is called immediately to initialize the Servlet.
  • The service method is called many times. Whenever there is a request, the service method will be called to respond to the request.
  • The destroy method is called only once, and when the Web application of the Servlet instance is unloaded, the method is called to release the resources currently occupied.

1.5 POST and GET requests (key points)

1.5.1 GET request

issue GET Main methods of request:
    (1)Enter in the browser URL Press enter
    (2)click<a>Hyperlinks
    (3)click submit Button, submit <form method="get">form 
GET Request characteristics:
    The request data is added to the request URL After the address, only a small amount of data can be submitted, which is unsafe

1.5.2 POST request

issue POST The method of request is as follows:
    click submit Button, submit <form method="post">form 
POST Characteristics of the request:
    Request data to be added to HTTP In the protocol body, a large amount of data can be submitted with good security

1.5.3 ServletRequest interface

(1) Basic concepts

  • javax.servlet.ServletRequest interface is mainly used to provide client request information to servlets, from which any request information can be obtained.
  • The Servlet container creates a ServletRequest object and passes it as a parameter to the service method of the Servlet.

(2) Common methods

1.5.4 HttpServletRequest interface

(1) Basic concepts

  • javax.servlet.http.HttpServletRequest interface is a sub interface of ServletRequest interface, which is mainly used to provide HTTP request information.
  • Unlike form data, when sending an HTTP request, the HTTP request header is directly set by the browser.
  • The request header data can be obtained directly through a series of get methods provided by the HttpServletRequest object.

(2) Common methods

1.5.5 ServletResponse interface

(1) Basic concepts

  • The javax.servlet.ServletResponse interface is used to define an object to help the Servlet send a response to the client.
  • The servlet container creates a ServletResponse object and passes it as a parameter to the service method of the servlet.

(2) Common methods

1.5.6 HttpServletResponse interface

(1) Basic concepts

  • The javax.servlet.http.HttpServletResponse interface inherits the ServletResponse interface to provide HTTP specific functions when sending responses.

(2) Common methods

1.5.7 use examples

// inherit HttpServlet
public class HelloWorld extends HttpServlet {
  // rewrite HttpServlet Medium doGet method
  protected void doGet(HttpServletRequest request, HttpServletResponseresponse)throws IOException, ServletException {
    // Set the response output code to avoid Chinese random code
    response.setContentType("text/html;charset=utf-8");
    // Get response output stream
    PrintWriter out= response.getWriter();
    // Output information using output stream
    out.println("<html><body> Hello world!</body></html>");
    //Close flow
    out.close();
  }
}
  • Case title
    • Use Servlet to obtain a random number between 1 and 100 in the server and send it to the client for display.

1.6 Chinese garbled code received by servlet (key)

1.6.1 reasons for receiving garbled code

  • When the browser submits the form, it will automatically encode the Chinese parameter values. When the Tomcat server receives the browser request, it will decode automatically. When the encoding and decoding methods are inconsistent, it will lead to garbled code.

1.6.2 resolve POST receiving garbled code

Set the encoding method before receiving:
    request.setCharacterEncoding("utf-8")
Tips:
    Must be called request.getParameter("name")Previous settings

1.6.3 solving GET receive garbled code

Re encode the received Chinese garbled code:
    // Chinese string of get request received
    String name = request.getParameter("name");
    // Re encode Chinese characters. The default encoding is ISO-8859-1
    String userName = new String(name.getBytes("ISO-8859-1"),"utf-8");

1.7 ServletConfig interface (familiar)

(1) Basic concepts

  • The javax.servlet.ServletConfig interface is used to describe the relevant configuration information of the Servlet itself and to pass the information to the Servlet configuration object during initialization.

(2) Configuration mode

<!-- stay web.xml Medium configuration ServletConfig Initialization parameters -->
<servlet>
  <servlet-name>actionservlet</servlet-name>
  <servlet-class>com.lagou.demo01.ActionServlet</servlet-class>
  <!-- to configure Serlvet Initialization parameters for -->
  <init-param>
    <!-- Parameter name -->
    <param-name>config</param-name>
    <!-- Parameter value -->
    <param-value>struts.xml</param-value>
  </init-param>
</servlet>

(3) Common methods

1.8 ServletContext interface (familiar)

(1) Basic concepts

  • The javax.servlet.ServletContext interface is mainly used to define a set of methods that a Servlet uses to communicate with its Servlet container.
  • When the server container starts, it will create a unique Servlet Context object for each project to realize information sharing and communication among multiple servlets.
  • In the Servlet, the ServletContext object can be obtained through the this.getServletContext() method.

(2) Configuration mode

<!--stay web.xml Medium configuration ServletContext Initialization parameters -->
<context-param>
  <param-name>username</param-name>
  <param-value>scott</param-value>
<context-param>
<context-param>
  <param-name>password</param-name>
  <param-value>tiger</param-value>
<context-param>

(3) Common methods

Topics: Java