DAY43 HTML Basics

HTML Basics

1. HTML Basics: Build the Basic Structure of Web Pages

1.1 Basic HTML Document Structure

An HTML web page has a fixed document structure, with all content wrapped in tags. The core structure includes 4 mandatory tags, corresponding to the following template (which is also the starting point of all web pages):

html 复制代码
<!DOCTYPE html>  <!-- Declare the document type as HTML5, must be placed at the top -->
<html>  <!-- Root tag of the web page, all other tags are nested in it -->
<head>  <!-- Header area, used to store meta information of the web page, not directly displayed on the page -->
    <meta charset="utf-8">  <!-- Set the web page encoding format to UTF-8 to ensure normal display of Chinese and other special characters -->
    <title>Chinese Test....</title>  <!-- Web page title, displayed on the browser tab bar -->
</head>
<body>  <!-- Main area, all visible content of the web page (text, images, links, etc.) are placed here -->
    This is the test content of the body....  <!-- Text content directly displayed on the page -->
</body>
</html>
Key Notes:
  • <!DOCTYPE html>: Declares that the document follows the HTML5 standard. Missing this declaration may cause the browser to parse the web page in compatibility mode, resulting in style confusion.
  • <meta charset="utf-8">: The core configuration to solve Chinese garbled characters. UTF-8 is currently the most universal character encoding format, supporting most languages in the world.

1.2 Core Common Tags: Enrich Web Page Content and Format

(1) Heading Tags: <h1> to <h6>

Used to define headings in web pages, from <h1> (largest, highest priority) to <h6> (smallest, lowest priority). They come with default bold and line breaks, and support the align attribute to set alignment (left for left alignment, center for center alignment, right for right alignment).

html 复制代码
<h1>h1 Font </h1>  <!-- Level 1 heading, the largest -->
<h3 align='center'>h3 Font </h3>  <!-- Level 3 heading, centered display -->
<h6 align='right'>h6 Font </h6>  <!-- Level 6 heading, right-aligned display -->
(2) Text Formatting Tags: Beautify Text Styles

Used to modify the format of text on the page. Common tags are as follows (all are inline tags, no automatic line breaks):

html 复制代码
<b>Bold Text</b>          <!-- Bold text -->
<i>Italic Text</i>          <!-- Italic text -->
<del>Strikethrough Text</del>      <!-- Text with strikethrough -->
<u>Underlined Text</u>            <!-- Text with underline -->
<small>Small Text</small>  <!-- Smaller text -->
<mark> Text with Yellow Highlight</mark> <!-- Text with yellow highlight background -->
<sub>2</sub>             <!-- Subscript text (such as 2 in H₂O) -->
<sup>2</sup>             <!-- Superscript text (such as 2 in 100m²) -->
Supplementary: Line Breaks and Paragraphs
  • <br>: Single tag, forced line break (no spacing).
  • <p>: Double tag, defines a paragraph with default spacing between paragraphs.
  • &nbsp;: Space entity, used to implement spaces in text (multiple consecutive spaces in HTML are parsed as a single space, so this entity is needed to implement multiple spaces).
html 复制代码
<p>Looking ahead to 2026, the policy path of China's real estate industry&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;has been clearly defined------</p>
<p>It also for the first time deploys "controlling incremental supply,<br><br>reducing inventory, and optimizing supply" in a coordinated manner</p>
(3) List Tags: Organize Structured List Content

Divided into unordered lists (<ul>) and ordered lists (<ol>), with list items defined by <li>.

html 复制代码
<!-- Unordered list: bullet points (default solid circles) are displayed before list items -->
<ul> 
    <li>List 1</li>
    <li>List 2</li>
    <li>List 3</li>
</ul>

<!-- Ordered list: sequential numbers (starting from 1 by default) are displayed before list items -->
<ol> 
    <li>List 1</li>
    <li>List 2</li>
    <li>List 3</li>
</ol>

The <a> tag is the core for realizing web page jumps. It specifies the target address through the href attribute and supports three common scenarios, which are also the basis of multi-page websites.

html 复制代码
<!-- 1. Link to an external website (absolute path, complete URL) -->
<a href="http://www.baidu.com">baidu</a>

<!-- 2. Link to a local file (relative path, HTML file in the same directory) -->
<a href="02.html">go to 2</a>

<!-- 3. Image link (use an image as the jump entry, nested <img> tag) -->
<a href="http://www.taobao.com"><img src="2.png"></a>
Key Notes:
  • Relative path: Applicable to local files, ./ indicates the current directory (can be omitted), and ../ indicates the parent directory.
  • Absolute path: Applicable to external websites, must include the complete protocol (http:///https://) and domain name.
(5) Image Tag: <img> for Inserting Image Resources

<img> is a single tag used to insert images into web pages, with the following core attributes:

html 复制代码
<img src="1.jpg" alt="Beautiful Woman" width="200" height="200">
  • src: Image source (relative or absolute path, required).
  • alt: Alternative text displayed when the image fails to load (improves user experience and search engine optimization).
  • width/height: Image width and height (supports pixel values px, unit can be omitted; also supports percentage %, relative to the size of the parent container).
(6) Inline Style: <style> for Setting Simple Page Styles

Simple styles can be defined in the web page header through the <style> tag, for example, setting the page background color:

html 复制代码
<head>
    <meta charset="utf-8">
    <title>Chinese Test....</title>
    <style>
        body {
            background-color: #E6E6FA;  /* Set the page background color to light purple */
        }
    </style>
</head>

1.3 Form Tag: <form> for Realizing User Data Submission

Forms are the core of web page interaction with users, used to collect information entered by users (such as username and password) and submit it to the backend server. The core structure and attributes are as follows:

(1) Core Attributes of the <form> Tag
  • action: Specifies the target address for form data submission (backend interface or server path, such as /login).
  • method: Specifies the submission method of form data, optional get (default) and post:
    • get: Data is appended to the end of the URL and transmitted to the server (visible, suitable for submitting a small amount of non-sensitive data).
    • post: Data is encapsulated in the request body and transmitted to the server (invisible, suitable for submitting sensitive data such as passwords and large amounts of data).
(2) <input> Tag: Core Input Control of Forms

<input> is a single tag, and the type of input control is specified through the type attribute. Common attributes and examples are as follows:

html 复制代码
<form action='login'>
    Username :<input type='text' name='username' required='required' placeholder='Please enter QQ account'>
    Password:<input type='password' name='userpass' required='required' placeholder='QQ password'>
    <input type='submit' value='Login'>
</form>
Key Attribute Explanations:
  • type: Type of input control, core values:
    • text: Single-line text input box (for entering ordinary text such as usernames).
    • password: Password input box (entered content is hidden as dots/asterisks).
    • submit: Submit button (triggers form submission when clicked).
    • reset: Reset button (clears all input content of the form when clicked).
  • name: Name of the input item (the backend server obtains the corresponding value through this name, required).
  • required: Mandatory item mark (the form cannot be submitted without this value, an HTML5 new feature).
  • placeholder: Prompt information for the input box (displayed when no input is made, disappears after input, improving user experience).
  • value: Default value of the control (such as the text on the submit button).

2. Practical Multi-Page Static Web Pages: Realize Page Jumps

Based on the above HTML basics, we can make multiple static web pages and realize mutual jumps between pages through the <a> tag.

1. Page 1 (01.html): Light Purple Background, Jump to 02.html

html 复制代码
<!DOCTYPE html>
<html >
<head>
    <meta charset="utf-8">
    <title>Chinese Test....</title>
    <style>
        body {
            background-color: #E6E6FA;  /* Light purple background */
        }
    </style>
</head>
<body >
    <h1>h1 Font </h1>
    <h3 align='center'>h3 Font </h3>
    <a href="02.html">go to 2</a>  <!-- Jump to 02.html in the same directory -->
</body>
</html>
(2) Page 2 (02.html): Red Background, Jump Back to 01.html
html 复制代码
<!DOCTYPE html>
<html >
<head>
    <meta charset="utf-8">
    <title>Chinese Test....</title>
    <style>
        body {
            background-color: #E6060A;  /* Red background */
        }
    </style>
</head>
<body >
    <h1>h1 Font </h1>
    <h3 align='center'>h3 Font </h3>
    <a href="01.html">go to 1</a>  <!-- Jump back to 01.html in the same directory -->
</body>
</html>

2. Implementation Effect

Place the two HTML files in the same directory, open either file, and click the hyperlink on the page to realize mutual jumps between the two pages, with each page having an independent background color, completing the construction of a simple multi-page website.

3. Build a Simple HTTP Server with C Language: Realize Login Verification Function

Through the HTML form, we can collect the user's login information, but to realize login verification (to determine whether the account and password are correct), backend server support is required. Below, we will build a simple HTTP server based on C language socket programming to realize the complete process of "receiving login requests → parsing parameters → verifying account and password → returning the corresponding page".

1. Core Function Decomposition of the Server

  1. Create a socket socket and listen on port 80 (the default port of the HTTP protocol).
  2. Bind the IP address and port, and wait for client (browser) connections.
  3. Receive the HTTP request from the client and parse the URL and parameters in the request.
  4. Process different requests: the root path / returns the login page, and the /login path parses the login parameters and performs verification.
  5. Send the corresponding HTML file to the client (return 01.html for successful login, 04.html for failed login).
  6. Close the connection and wait for the next client request in a loop.

2. Complete Server Code and Annotations

c 复制代码
#include <fcntl.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

typedef struct sockaddr*(SA);  // Simplify the definition of sockaddr structure pointer

// Send file content to the client (browser)
int send_file(int conn, char* filename)
{
    // Open the HTML file in read-only mode
    int fd = open(filename, O_RDONLY);
    if (-1 == fd)
    {
        perror("open");
        return 1;
    }
    // Read file content in a loop and send it to the client
    char buf[4096] = {0};
    int rd_ret;
    while ((rd_ret = read(fd, buf, sizeof(buf))) > 0)
    {
        send(conn, buf, rd_ret, 0);  // Send the read file content
        memset(buf, 0, sizeof(buf)); // Clear the buffer
    }
    close(fd);  // Close the file descriptor
    return 0;
}

int main(int argc, char** argv)
{
    // 1. Create a listening socket (TCP protocol)
    int listfd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == listfd)
    {
        perror("socket");
        return 1;
    }

    // 2. Configure the server address structure
    struct sockaddr_in ser, cli;
    bzero(&ser, sizeof(ser));  // Clear the structure
    bzero(&cli, sizeof(cli));
    ser.sin_family = AF_INET;  // Use the IPv4 protocol
    ser.sin_port = htons(80);  // Bind to port 80 (default HTTP port, requires sudo to run)
    ser.sin_addr.s_addr = INADDR_ANY;  // Listen on all available network interfaces

    // 3. Bind the socket to the address
    int ret = bind(listfd, (SA)&ser, sizeof(ser));
    if (-1 == ret)
    {
        perror("bind");
        return 1;
    }

    // 4. Start listening (maximum number of queued connections is 3)
    listen(listfd, 3);
    socklen_t len = sizeof(cli);

    // 5. Wait for client connections in a loop (provide services continuously)
    while (1)
    {
        // Accept the client connection and create a communication socket
        int conn = accept(listfd, (SA)&cli, &len);
        if (-1 == conn)
        {
            perror("accept");
            return 1;
        }

        // 6. Receive the HTTP request sent by the client
        char buf[1024] = {0};
        ret = recv(conn, buf, sizeof(buf), 0);
        if (ret <= 0)
        {
            close(conn);
            continue;
        }

        // 7. Parse the HTTP request line (GET /xxx HTTP/1.1)
        char* method = NULL;  // Request method (GET/POST)
        char* url = NULL;     // Request path
        char* ver = NULL;     // HTTP version

        method = strtok(buf, " ");
        url = strtok(NULL, " ");
        ver = strtok(NULL, "\r");

        // 8. Process different request paths
        if (url && 0 == strcmp(url, "/"))
        {
            // Root path request: return the login page (03.html)
            send_file(conn, "./03.html");
        }
        else if (url && 0 == strncmp(url, "/login", 6))
        {
            // Login request: parse the username and password in the URL
            char* name = NULL;
            char* pass = NULL;
            char* end = NULL;

            // Parse the username (URL format: /login?username=zhangsan&userpass=123)
            name = strchr(url, '=');
            if (!name) { send_file(conn, "./04.html"); close(conn); continue; }
            name += 1;

            end = strchr(name, '&');
            if (!end) { send_file(conn, "./04.html"); close(conn); continue; }
            *end = '\0';  // Truncate the & symbol after the username

            // Parse the password
            pass = strchr(end + 1, '=');
            if (!pass) { send_file(conn, "./04.html"); close(conn); continue; }
            pass += 1;

            // 9. Verify the username and password (hard-coded test: zhangsan/123)
            if (0 == strcmp(name, "zhangsan") && 0 == strcmp(pass, "123"))
            {
                send_file(conn, "./01.html");  // Verification successful: return 01.html
            }
            else
            {
                send_file(conn, "./04.html");  // Verification failed: return 04.html (wrong password)
            }
        }

        // 10. Close the communication socket and release resources
        close(conn);
    }

    // 11. Close the listening socket (not executed in the actual loop)
    close(listfd);
    return 0;
}

3. Supporting Page Preparation

Place the following 4 HTML files in the same directory as the server code:

  1. 01.html: Login success page (light purple background).
  2. 02.html: Auxiliary jump page (red background).
  3. 03.html: Login form page (core form, action='login').
  4. 04.html: Login failure page (displays "Wrong Password").
html 复制代码
<!-- 04.html Login Failure Page -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Login</title>
</head>
<body>
    <mark>
        <h1> Wrong Password</h1>
    </mark>
</body>
</html>

4. Practical Deployment and Testing: Complete the Full Login Process

1. Compile the Server Code

Use gcc to compile the C language code and generate an executable file:

bash 复制代码
gcc http_server.c -o http_server

2. Run the Server

Since port 80 (a privileged port) is bound, it needs to be run with sudo privileges:

bash 复制代码
sudo ./http_server

3. Browser Test Login Process

  1. Open a browser, enter http://localhost (or the server's IP address) in the address bar, and press Enter to display the 03.html login form.
  2. Enter the username "zhangsan" and password "123" in the form, and click the submit button.
  3. Verification successful: The browser jumps to 01.html (light purple background page).
  4. Enter an incorrect username or password (such as "zhangsan"/"456"), and click the submit button.
  5. Verification failed: The browser jumps to 04.html (displays "Wrong Password").

4. Test Effect Description

  • During the server operation, it will continuously print the HTTP request information of the client, which is convenient for debugging.
  • The form submission uses the get method, and the username and password will be appended to the URL (e.g., http://localhost/login?username=zhangsan&userpass=123), and the server obtains the verification parameters by parsing this URL.

5. Common Problems and Pitfall Avoidance Guide

  1. Failed to bind to port 80 : Port 80 is a privileged port and cannot be bound by ordinary users. You need to run the server with sudo.
  2. Failed to open HTML files : Ensure that the HTML files are in the same directory as the server executable file, and the file names are consistent with the parameters of the send_file function in the code (note case sensitivity).
  3. Failed to parse login parameters : Ensure that the name attributes of the <input> tags in the form are "username" and "userpass", consistent with the parameter names parsed by the server.
  4. Chinese garbled characters : All HTML files must add <meta charset="utf-8"> to ensure uniform character encoding.
  5. The server cannot provide continuous services: The server adopts a single-threaded processing mode and can only respond to one client request at a time. Multiple clients accessing at the same time will be queued. It can be optimized through multi-threading/multi-processing later.

6. Summary and Expansion

1. Core Knowledge Point Combustion

  1. HTML Basics: Master the basic document structure and the use of core tags (hyperlinks, images, forms), and be able to make static web pages and user interaction forms.
  2. Multi-Page Jumps: Realize mutual jumps between local pages through the relative path of the <a> tag, and build a simple multi-page website.
  3. C Language Socket Programming: Master the core process of the HTTP server (create socket → bind → listen → accept connection → parse request → return response).
  4. Login Verification Implementation: Realize simple account and password verification by parsing the URL parameters of the get request, and return the corresponding page.

2. Expansion Directions

  1. Switch to POST Request : Optimize the form submission method, set method to post, and the server obtains parameters by parsing the request body to avoid exposing the password in the URL.
  2. Support More Static Resources: Expand the server functions to support loading images, CSS, and JavaScript files, beautify web page styles, and realize dynamic effects.
  3. Multi-Threaded/Multi-Process Optimization: Transform the server into a multi-threaded or multi-process mode to support responding to multiple client requests at the same time and improve service concurrency capability.
  4. Improve Error Handling: Add 404 pages (page not found) and 500 pages (internal server error) to improve user experience.
  5. Persistent Storage of Accounts and Passwords: Combine with the SQLite3 database to store accounts and passwords in the database, realize dynamic addition and modification of user information, and replace the hard-coded verification method.
相关推荐
七夜zippoe6 小时前
Python并发与并行编程深度剖析:从GIL原理到高并发实战
服务器·网络·python·并发·gil
前端 贾公子6 小时前
剖析源码Vue项目结构 (一)
前端·javascript·vue.js
狂龙骄子6 小时前
jQuery表单验证插件全攻略
前端·javascript·jquery·jquery表单验证
YJlio6 小时前
PsPing 学习笔记(14.4):TCP/UDP 延迟测试——从单包 RTT 到抖动分析
笔记·学习·tcp/ip
广东大榕树信息科技有限公司6 小时前
如何通过动力环境监控系统提升决策效率?
运维·网络·物联网·国产动环监控系统·动环监控系统
忆_恒心6 小时前
eNSP网络实验:一站式掌握DNS、HTTP、FTP服务器配置全攻略
服务器·网络·网络协议·计算机网络·http·智能路由器
谁在夜里看海.6 小时前
【Linux-网络】HTTP的清风与HTTPS的密语
linux·网络·http·https
HIT_Weston6 小时前
82、【Ubuntu】【Hugo】搭建私人博客:文章目录(一)
linux·运维·ubuntu
守城小轩6 小时前
轻量级HTTP&Socks代理GOST: 搭建 HTTP(S)和Socks代理
网络·网络协议·http·浏览器网路