This is the 14th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

1 Basic Concepts

1.1 C/S architecture concept

  • C/S architecture (Client/Server, Client/Server mode), is a relatively early software architecture, but also a very common structure in life. This structure distributes the business that needs to be handled reasonably between the client and the 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 client interface and functionality can be very rich.
    • The load on the application server is light.
  • Fast response.

  • The main disadvantages of the C/S architecture are as follows:

    • Narrow application area and fixed user group.
    • Maintenance and upgrade costs are high, and all clients need to update versions.

1.2 B/S architecture concept

  • B/S architecture (Browser/Server and Browser/Server mode), after the rise of the Internet software architecture, the structure function of the system for the main business logic on the Server side, a handful of business logic in the Browser, the Browser is usually responsible for the task into the interaction with the user, the Server is usually responsible for data management.

  • The main advantages of the B/S architecture are as follows:

    • You don’t need to install a client, just have a browser.
    • Wide range of applications, user groups are not fixed.
    • Through the permission control to achieve the purpose of multi-client access, interactive.
    • Low maintenance and upgrade costs, no need to update all client versions.
  • The main disadvantages of the B/S architecture are as follows:

    • The application server is overloaded.
    • The interface and functionality of the browser can be as rich as that of the client.
    • Cross-browser is not satisfactory, more difficult to adapt.

1.3 JavaWeb concepts

  • Web is the original meaning of the Web page, which refers to the resources on the Internet for external access.

  • Resources on the Internet for external access are divided into the following two types:

    • Static resources: Basically, the data in a Web page for people to browse is always the same.
    • Dynamic resources: mainly refers to the Web page for people to browse the data generated by the program, different points of time to visit the page to see different content.
  • JavaWeb mainly refers to the use of Java language for dynamic Web resource development technology, is to solve the related Web Internet domain technology sum.

Early B/S architecture

Later B/S architecture

2 the HTTP protocol

2.1 Concepts of HTTP

  • HyperText Transfer Protocol (HTTP) is an application layer Protocol developed by W3C (World Wide Web Consortium). It is used to regulate the data format of communication between browsers and Web servers, mainly involving the format of sending requests by browsers and the format of responding by servers.

  • HTTP is usually carried on top of TCP, while the protocol carried on top of TLS or SSL is often referred to as HTTPS.

  • The default HTTP port number is 80 and HTTPS port number is 443.

2.2 HTTP Request Format

  • The request message that the client sends an HTTP request to the server consists of the request line, the request header, the blank line, and the request body.
A request line is used to specify the request type, resource to be accessed, and HTTP version. The format of the request line is as follows: Request Type Path protocol version (1.1) The request header is the key:value that follows the first line of the request and describes the additional information to be used by the server. Host request length Blank browser-related information lines are blank lines in the request header, even if the following request data is blank lines must be blank lines. The request body, also called request data, can add any other dataCopy the code

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
Copy the code

2.3 HTTP Response Format

  • Generally, the server will return an HTTP response message after receiving and processing the request from the client, including the response line, response header, blank line, and response body.
The response line describes the HTTP version and status code and the status message in the following format: Protocol version (1.0 1.1) Status code (200 success 404 Path error 500 Service error) Status information The response header describes additional information to be used by the client in the format of key:value. Blank lines are empty lines in the response header, even if subsequent request data is empty. The response body is used to send text information back to the client from the server.Copy the code

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 an HTML page</h1></body> </html>
Copy the code

3 Tomcat Server

3.1 Basic Concepts

  • Tomcat, which means male cat, was originally developed by Sun software architect James Duncan Davidson, who later helped make it an open source project that Sun contributed to the Apache Software Foundation.

  • Tomcat server is an open source lightweight Web application server. It is widely used in small and medium-sized systems and small concurrency situations. It is the first choice for developing and debugging Servlet and JSP programs.

3.2 Installation Methods

  • Tomcat.apache.org/

3.3 Directory Structure

  • Bin stores binary executable files and scripts.
  • Conf stores various configuration files.
  • Lib is used to store jar packages that need to be loaded to run Tomcat.
  • Logs Stores log files generated during Tomcat running.
  • Temp stores temporary files generated when Tomcat is running.
  • Webapps mainly stores applications. When Tomcat is started, the applications in this directory will be loaded.
  • Work mainly houses compiled files of Tomcat at runtime, such as JSP compiled files.

3.4 Startup and Shutdown

  • Start the way

Use the batch file startup.bat in the bin directory to start the Tomcat server. The Tomcat server is successfully started if a number of milliseconds is displayed.

  • Close the way

Use the batch file shutdown.bat in the bin directory to shutdown the Tomcat server.

  • Matters needing attention

    • Before starting the Tomcat server, install JDK and configure environment variable JAVA_HOME. If you want the Tomcat server to be started in any path, you need to configure environment variable CATALINA_HOME.

    • Startup information garbage characters are handled: logging properties file modification for Java. The util. Logging. ConsoleHandler. Encoding = GBK

3.5 Configuration File

  • The server. XML file is the main configuration file for the server. You can set the port number, set the domain name or IP address, load the project by default, request code, and so on.

<Connector port="8888" protocol="HTTP / 1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
Copy the code
  • 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"/>
Copy the code

4 The concept and use of Servlets

4.1 Basic Concepts

  • Server applets (Servlets) are short for Java servlets. They are called small service programs or service connectors. They are server-side programs written in Java language.

  • Servlet is used to complete the response processing of client requests under THE B/S architecture, that is, to interactively browse and generate data and generate dynamic Web content.

4.2 Servlet programming steps

  • Set up a Java Web Application project and configure the Tomcat server.
  • Custom classes implement the Servlet interface or inherit the HttpServlet class (recommended) and rewrite the Service method.
  • Configure the information about the custom class to the web.xml file and start the project as follows:
<! -- Config Servlet --> 
<servlet>

<! HelloServlet is an alias for the Servlet class -->

<servlet-name> HelloServlet </servlet-name>

<! -- com. Lagou. Task01. HelloServlet is real Servlet class contains the path name -- -- > 
<servlet-class> com.111.task01.HelloServlet </servlet-class>

</servlet>

<! -- Mapping Servlet --> 
<servlet-mapping>

<! -- HelloServlet is an alias for the Servlet class and must be the same as the name above --> 
<servlet-name> HelloServlet </servlet-name>

<! -- /hello is the address for the browser -->

<url-pattern> /hello </url-pattern>

</servlet-mapping>
Copy the code
  • The browser can be accessed as follows:
http://localhost:8080/ Contents of the project path /url-patternCopy the code

4.3 the Servlet interface

(1) Basic concepts

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

(2) Common methods

Method statement Function is introduced
Void init (ServletCon fi g con fi g) Called by the servlet container to indicate to the servlet that the servlet is being put into the service
void service(ServletRequest req, ServletResponse res) Called by the servlet container to allow the servlet to respond to requests
ServletCon fi g getServletCon fi g () Return a ServletConfig object that contains the initialization and startup parameters of this servlet
String getServletInfo() Returns information about the servlet, such as author, version, and copyright
void destroy() Called by the servlet container to indicate to the servlet that the servlet is exiting the service

4.5 GenericServlet class

(1) Basic concepts

  • Javax.mail. Servlet. GenericServlet class is mainly used to define a generic, has nothing to do with the agreement of the servlet, the class implements the servlet interface.

  • If you write general-purpose servlets, you simply override the Service abstraction method.

(2) Common methods

Method statement Function is introduced
abstract void service(ServletRequest req, ServletResponse res) Invocation by the servlet container allows the servlet to respond to requests

4.6 the HttpServlet class

(1) Basic concepts

  • Javax.mail. Servlet. HTTP. The HttpServlet class is an abstract class and inherit the GenericServlet class. Subclasses of this class must override at least one method to create HTTP servlets suitable for web sites.

(2) Common methods

Method statement Function is introduced
void doGet(HttpServletRequest req, HttpServletResponse resp) Process client GET requests
void doPost(HttpServletRequest req, HttpServletResponse resp) Process client POST requests
void init() Initialization is performed
void service(HttpServletRequest req, HttpServletResponse resp) Call the doGet or doPost method depending on the request
void destroy() Resources are released when instances are deleted

4.7 Servlet life cycle

  • The constructor is called only once, when the Servlet is first requested to create an instance of the Servlet.
  • The init method is called only once, immediately after the Servlet instance is created to initialize the Servlet. The service method is called multiple times, and is called every time a request is made to respond to the request.
  • The destroy method is called only once, before the Web application in which the Servlet instance resides is uninstalled, to release the currently occupied resources.

5 POST and GET requests

5.1 GET request

The main ways to send GET requests are as follows: (1) Enter the URL in the browser and press Enter; (2) click the hyperlink <a>; (3) Click the Submit button to submit <form method= "GET" > Request data is appended to the request URL, and only a small amount of data can be submitted, which is not secureCopy the code

5.2 a POST request

The methods to send a POST request are as follows: Click submit button to submit <form method= "POST" > The features of POST request are as follows: Request data is added to the HTTP protocol body, and large amounts of data can be submittedCopy the code

5.3 ServletRequest interface

(1) Basic concepts

  • Javax.mail. Servlet. ServletRequest interface is mainly used to provide the client request information to the servlet, you can get to any requests for information.

  • The Servlet container creates a ServletRequest object and passes it as a parameter to the Servlet’s Service method.

(2) Common methods

Method statement Function is introduced
String getParameter(String name) Returns the value of the request parameter as a string, or null if it does not exist
String[] getParameterValues( String name) Returns an array of string objects containing all the values that a given request parameter has, or null if the parameter does not exist
Enumeration getParameterNames() Returns an enumeration of string objects containing the names of the parameters contained in this request. If the request has no parameters, the method returns an empty enumeration
Map<String, String[]> getParameterMap() Returns a key-value pair of the request parameter. One key can correspond to multiple values
String getRemoteAddr() Returns the IP address of the client or last proxy that sent the request
int getRemotePort() Returns the port number of the client or last proxy that sent the request

5.4 it interface

(1) Basic concepts

  • Javax.mail. Servlet. HTTP. It interface ServletRequest interface as part of the interface, the function of the HTTP request is mainly used to provide information.

  • Unlike form data, the HTTP request header is set directly by the browser when an HTTP request is sent.

  • Request header data can be obtained directly through a series of GET methods provided by the HttpServletRequest object.

(2) Common methods

Method statement Function is introduced
String getRequestURI() Returns the resource path information for this request
StringBu ff er getRequestURL () Returns the full path information for this request
String getMethod() Returns the name of the HTTP method that made the request, such as GET, POST
String getQueryString() Returns the parameters attached to the request following the path
String getServletPath() Returns the path portion of this request calling the servlet

5.5 ServletResponse interface

(1) Basic concepts

  • Javax.mail. Servlet. ServletResponse interface is used to define an object to help the servlet to the client sends a response.

  • The Servlet container creates a ServletResponse object and passes it as a parameter to the Servlet’s Service method.

(2) Common methods

Method statement Function is introduced
PrintWriter getWriter() Returns a PrintWriter object that sends character text to the client
String getCharacterEncoding() Gets the encoding of the response content
void setContentType(String type) If the response has not been submitted, the content type of the response sent to the client is set. Content types can include character encoding specifications, such as text/ HTML; charset=UTF-8

5.6 the HttpServletResponse interface

(1) Basic concepts

  • Javax.mail. Servlet. HTTP. HttpServletResponse interface inheritance ServletResponse interface, in order to send to provide the function of the specific to the HTTP response.

(2) Common methods

Method statement Function is introduced
void sendRedirect(String location) Sends a temporary redirect response to the client using the specified redirect location URL

6 The Servlet receives Chinese garbled characters

6.1 Cause of Receiving Garbled Characters

  • The browser automatically encodes the Chinese parameter values when submitting the form. When the Tomcat server receives a browser request, it automatically decodes it. When the encoding is inconsistent with the decoding method, garbled characters will result.

6.2 Troubleshooting Garbled Characters received in POST

Set encoding: before receiving the request. SetCharacterEncoding (" utf-8 ") tip: must be in the call request. The getParameter (" name ") set beforeCopy the code

6.3 Resolving Garbled Characters received from GET

String name = request.getParameter("name"); String userName = new String(name.getBytes(" ISo-8859-1 "), "UTF-8 ");Copy the code

7 ServletCon fi g interface

(1) Basic concepts

  • The Javax.servlet.Servletcon fig interface is used to describe the relevant configuration information of the servlet itself and to pass this information to the servlet configuration object during initialization.

(2) Configuration mode

<! Set ServletConfig initialization parameters in web.xml --> <servlet>

<servlet-name>actionservlet</servlet-name> 
<servlet-class>com.111.demo01.ActionServlet</servlet-class> <! Set Serlvet initialization parameters

<init-param>

<! -- Parameter name --> <param-name>config</param-name>

<! -- Parameter value --> <param-value>struts.xml</param-value>

     </init-param>

</servlet>
Copy the code

(3) Common methods

Method statement Function is introduced
String getServletName() Returns the alias of the Servlet
String getInitParameter(String name) Returns a string containing the value of the initialization parameter, or null if it does not exist
Enumeration getInitParameterNames() Returns the name of the servlet’s initialization parameter as an enumeration of the string object, or an empty enumeration if the servlet has no initialization parameter
ServletContext getServletContext() Returns a reference to the ServletContext in which the caller is executing

8 the ServletContext interface

(1) Basic concepts

  • Javax.mail. Servlet. The ServletContext interface is mainly used to define a set of methods, the servlet USES these methods to communicate with its servlet container.

  • The server container creates a unique ServletContext object for each project at startup, which enables information sharing and communication between servlets.

  • The ServletContext object is obtained in the Servlet using the this.getServletContext() method.

(2) Configuration mode

<! Set ServletContext initialization parameters in web.xml -->
<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>
Copy the code

(3) Common methods

Method statement Function is introduced
String getInitParameter(String name) Returns a string containing the value of the initialization parameter, or null if it does not exist
Enumeration getInitParameterNames() Returns the name of the servlet’s initialization parameter as an enumeration of the string object, or an empty enumeration if the servlet has no initialization parameter
String getRealPath(String path) Returns a string containing the actual path for the given virtual path
String getContextPath() Returns the main path associated with this context
InputStream getResourceAsStream(String path) Returns the resource at the specified path as an InputStream object
void setAttribute(String name, Object object) Binds the specified property name and value to the current object
Object getAttribute(String name) Gets the property value based on the name of the property executed
void removeAttribute(String name) Deletes the specified attribute name information

9 the Servlet + JDBC applications

  • You can use JDBC technology to access the database in servlets,

    • Common functions are as follows: Queries DB data and generates a display page, for example, lists.
    • Receive request parameters, and then operate on DB, such as: registration, login, change password, and other functions.
  • In order to facilitate reuse and maintenance, Data Access Object (DAO) mode is often used to encapsulate database operations independently.

  • DAO Factory (Factory mode)

Factory class: Encapsulates the creation details of an object and provides the caller with an object that meets the requirements.

9.2 Redirection and Forwarding

9.2.1 Overview of redirection

(1) The concept of redirection

  • First, the client browser sends an HTTP request. When the Web server accepts the request, it sends a 302 status code response with the corresponding new location to the client browser. When the client browser finds the 302 response, it automatically sends a new HTTP request with the new LOCATION URL. The server finds the resource based on this request and sends it to the client.

(2) implementation of redirection

  • Implement redirect need javax.mail. Servlet. HTTP. HttpServletResponse interface in the following ways:
Method statement Function is introduced
void sendRedirect(String location) Sends a temporary redirect response to the client using the specified redirect location URL

(3) Principle of redirection

(4) Characteristics of redirection

  • After the redirect, the URL in the browser address bar changes.
  • The redirection destroys the previous Request object and creates a new Request object.
  • The redirected URL can be another project.

9.2.2 Overview of Forwarding

(1) The concept of forwarding

  • One Web component (Servlet/JSP) passes the unfinished processing through the container to another Web component for further processing, and the forwarding components share Request and Response objects.

(2) The realization of forwarding

  • Bind data to the Request object
Method statement Function is introduced
Object getAttribute(String name) Returns the specified attribute value as an object, or null if the given name attribute does not exist
void setAttribute(String name,Object o) Store property values in this request
  • Obtain the forwarder object
Method statement Function is introduced
RequestDispatcher getRequestDispatcher(String path) Returns a RequestDispatcher object that acts as a wrapper for the resource on the given path
  • Forwarding operation
Method statement Function is introduced
void forward(ServletRequest request, ServletResponse response) Forwarding requests from one servlet to another asset (servlet, JSP file, or HTML file) on the server

(3) Characteristics of forwarding

  • After forwarding, the URL in the browser address bar does not change. Request objects are shared during forwarding.
  • The forwarded URL cannot be another project.

(4) Comparison between redirection and forwarding

9.3 Servlet thread Safety

  • When the server receives a request, it starts a thread to process the request.

  • By default, the server creates only one object instance per Servlet. Thread-safety issues can occur when multiple requests access the same Servlet and multiple threads access the same Servlet object.

  • Multithreaded concurrent logic, need to use synchronized code lock processing, but try to avoid using.

9.4 Status Management

  • Web applications communicate over HTTP, a “stateless” protocol that disconnects once a server has responded to a client’s request, only to be re-connected with the same client’s next request.

  • Server programs are sometimes requests that need to be determined if they are made for the same customer, such as multiple purchases by the customer. Therefore, it is necessary to track a series of requests from the same customer.

  • The multiple interactions between the browser and the server are taken as a whole, and the data involved in the multiple interactions is saved, that is, state management.

  • The data state of multiple interactions can be saved on the client side or on the server side. Status management is mainly divided into the following two types:

    • Client side management: Saves state on the client side. Based on Cookie technology.
    • Server management: Saves state on the server side. Based on Session technology.

9.5 the Cookie technology

9.5.1 Basic Concepts

  • Cookie means “Cookie”, here refers to the client saves in the form of a “name-value” technology.
  • When the browser sends a request to the server, the server responds with data in a set-cookie header to the browser, which then saves the data as a text file.
  • When the browser visits the server again, it sends this data to the server in the form of a Cookie header.

9.5.2 Relevant methods

  • . Use javax.mail. Servlet. HTTP cookies class constructor to realize the creation of a Cookie.
Method statement Function is introduced
Cookie(String name, String value) Constructs an object by specifying a value as an argument
  • Using the javax.mail. Servlet. HTTP. Members of the HttpServletResponse interface can realize the add of cookies.
Method statement Function is introduced
void addCookie(Cookie cookie) Adds the object specified by the parameter to the response
  • Use javax.mail. Servlet. HTTP. It the members of the interface methods to realize the Cookie object access.
Method statement Function is introduced
Cookie[] getCookies() Returns all Cookie objects contained in this request
  • . Use javax.mail. Servlet. HTTP cookies class constructor properties during the Cookie object access and modification.
Method statement Function is introduced
String getName() Returns the name in this Cookie object
String getValue() Returns the value of this Cookie object
void setValue(String newValue) Sets the value of the Cookie

9.5.3 Cookie life cycle

  • By default, the browser keeps Cookie information in memory and the Cookie disappears when the browser is closed.

  • If you want the Cookie information to remain valid after closing the browser, you can use the member method of the Cookie class to do so.

Method statement Function is introduced
int getMaxAge() The maximum lifetime of the cookie returned in seconds
void setMaxAge(int expiry) Set the maximum retention time for cookies (seconds)

9.5.4 Characteristics of Cookies

  • Cookie technology is not suitable for storing all data and is only used by programmers to store small amounts of non-sensitive information for the following reasons:

    • It is not safe to save status data in the browser.
    • The amount of data to be saved is limited to about 4KB.
    • Only string information can be saved.
    • You can disable it through your browser.

9.6 the Session technology

9.6.1 Basic Concepts

  • Session, meaning “Session”, is a technique used to maintain the association between a client and a server.

  • When the browser visits the server, the server allocates a space in memory on the server side for each browser to create a Session object, which has an ID attribute with a unique value, called the SessionId, and the server assigns this to the server

The SessionId is sent to the browser as a Cookie for storage.

  • When the browser visits the server again, it sends the Session ID to the server. The server can search for the corresponding Session object based on the Session ID

9.6.2 Relevant methods

  • Use javax.mail. Servlet. HTTP. It the members of the interface methods access to the Session.
Method statement Function is introduced
HttpSession getSession() Returns the current Session associated with this request, or creates one if there is none
  • Using javax.mail. Servlet. HTTP. Members of the HttpSession interface method to judge and access.
Method statement Function is introduced
boolean isNew() Check whether it is a newly created Session
String getId() Gets the Session number
  • Use the javax.mail. Servlet. HTTP. Members of the HttpSession interface method realized the management of properties.
Method statement Function is introduced
Object getAttribute(String name) Returns the object bound with the specified name in this session, or null if no object is bound under that name
void setAttribute(String name, Object value) Binds the object to this session with the specified name
void removeAttribute(String name) Removes the object bound to the specified name from this session

9.6.3 Session life Cycle

  • To save server memory resources, the server automatically deletes Session objects that are idle for a long time. The default timeout limit is 30 minutes.

  • Using javax.mail. Servlet. HTTP. Members of the HttpSession interface method implementation failure to get and set.

Method statement Function is introduced
int getMaxInactiveInterval() Obtaining failure time
void setMaxInactiveInterval(int interval) Set expiration time
  • You can configure the web. XML file to change the expiration time.
<session-config>

    <session-timeout>30</session-timeout>

</session-config>
Copy the code

9.6.4 Session Characteristics

  • Data is safer.
  • The data types that can be saved are rich, whereas cookies can only hold strings.
  • More data can be stored, while cookies hold about 4KB.
  • Data stored on the server occupies the memory space of the server. If too much information is stored and too many users are used, the server performance will be seriously affected.