Web basics

Published 2026-07-29 10:34 Updated 2026-10-13 17:14 1264 words 7 min read ... Page views AI-reviewed An AI proof-read this post, but it still deserves a careful read. AI-rewritten Someone else wrote the original; AI helped me rewrite and polish it.

AI-reviewed An AI proof-read this post, but it still deserves a careful read.

This article introduces the basic composition and development model of Web applications, including front-end, back-end, database and server, and compares the two development models of front-end integration and separation. The front-end integration mode has a high degree of coupling, while the front-end separation mode achieves independent development through interface conventions to reduce dependence. The article also details the responsibilities of Views, Controllers and Models in the MVC hierarchical architecture, as well as the use methods and considerations of core components such as HttpServletRequest, HttpServletResponse, HttpSession, Cookies and ServletContext in the Servlet API, emphasizing issues such as security and thread safety.

Web basics

Basic components of Web applications

Web applications usually consist of front-end, back-end, database, and Web server.

  • front end: Runs in the browser and is responsible for page display, user interaction and some data processing. Common technologies include HTML, CSS, JavaScript, jQuery, and Bootstrap.

  • rear end: Runs in the server and is responsible for receiving requests, processing business, accessing the database, and returning results. Common technologies in the Java Web include Servlets and Spring MVC.

  • interface: Agreed on the request address, request method, parameter format and response format to enable the front and back ends to collaborate.

Front-end integrated development

The front-end pages and back-end programs are deployed in the same project or the same server application. After starting the service, page resources and back-end interfaces usually run together.

In this model, in addition to processing business data, the backend may also be responsible for page jumps and server-side page rendering. The front-end and back-end rely heavily on the same project structure and page template, so the degree of coupling is usually high.

Take the login page as an example:

image-001
image-001

Separate development of front and rear ends

The front-end and back-end are two relatively independent application development and deployment. The front end is responsible for page display, user interaction and routing jumps, and the back end is responsible for business processing and data access.

The two parties exchange data according to the interface document, and the common data format is JSON. Usually, the front end sends request data to the back end, the back end processes it and returns a JSON result, and the front end updates the page based on the result.

This model can reduce the direct dependence on code and deployment between the front and back ends, and support parallel development between the front and back ends, but both parties still need to abide by the interface agreement.

image-002
image-002

MVC hierarchical model

MVC divides application responsibilities into Model, View, and Controller:

image-003
image-003

View View Level

Responsible for displaying data and receiving user actions. In front-end integrated projects, the View may be a JSP or HTML template; in front-end separated projects, the View is usually implemented by a separate front-end application.

Controller Controller Layer

Responsible for receiving client requests, reading request parameters, calling the business layer, and returning processing results to the client.

In front-end integrated mode, Controllers may return a page view; in front-end separated mode, Controllers typically return JSON data.

Model layer

Responsible for business data and processing logic. Actual Java Web projects usually continue to be split into:

  • Service Layer: Handle business logic and transactions.

  • DAO or Repository layer: Access a database or other data source.

MVC describes the division of responsibilities, and the specific layering method in actual projects can be adjusted according to the framework and business scale.

Servlet API

The Servlet API provides a set of interfaces and classes required for Java Web development to process HTTP requests, generate HTTP responses, manage sessions, and access Web application contexts.

Add Maven dependencies

The following dependencies apply to javax.servlet Namespace Servlet 4.0 projects:

<dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

provided Represents that this dependency is required at compile time, but is usually provided at runtime by a Servlet container such as Tomcat.

create a Servlet

Servlets can map with URL paths through annotations. When the client accesses the corresponding path, the Servlet container calls the corresponding method:

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/test")
public class TestController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 读取请求参数
        // 调用业务层
        // 将结果写入响应
        System.out.println("客户端访问了 /test,执行了 TestController 的 service 方法");
    }
}

Servlet instances are typically created and managed by containers. An HTTP request corresponds to a set of request objects and response objects, but multiple requests may be processed by the same Servlet instance, so don’t save data from a single request in the Servlet instance field.

HttpServletRequest request object

HttpServletRequest Encapsulates the HTTP request sent by the client. After a request is processed, the request object is usually no longer used.

Common operations include:

  • Method to obtain the request:request.getMethod()。

  • Get the request URL:request.getRequestURL()。

  • Get the context path:request.getContextPath()。

  • Get request header:request.getHeader("请求头名称")。

  • Get individual request parameters:request.getParameter("参数名")。

  • Get multiple parameters with the same name:request.getParameterValues("参数名")。

  • Save request range attributes:request.setAttribute("name", value)。

  • Read request range attributes:request.getAttribute("name")。

Request attributes are often used to pass data when forwarding within the server, and their lifetime usually only covers the current request.

HttpServletResponse response object

HttpServletResponse Used to set the status code, response header, character encoding and response body.

response.setContentType("text/plain;charset=UTF-8");
response.getWriter().write("响应给浏览器的数据");

Common operations include:

  • Set the response status code.

  • Set the response header.

  • Set the response content type and character encoding.

  • Write the response body via a character stream or byte stream.

  • Perform the redirect.

HttpSession session object

HttpSession Used to save data related to a client session on the server. the first call to request.getSession() When, if the current session does not exist, the container usually creates a new session.

HttpSession session = request.getSession();
session.setAttribute("test", "test");
Object value = session.getAttribute("test");

Browsers usually carry session identifiers through session cookies, allowing subsequent requests to be associated with the same HttpSession。

Sessions are destroyed after timeout, proactive failure, or server processing. The timeout period is determined by the server or application configuration and is not fixed to 20 minutes.

Cookies are small pieces of data sent by the server to the browser and stored by the browser in accordance with rules. When the browser subsequently accesses the matching address, it can send a Cookie to the server with the request.

Write cookies to clients

Cookie cookie = new Cookie("username", "tom");
cookie.setMaxAge(3600);
response.addCookie(cookie);

Read cookies in requests

Cookie[] cookies = request.getCookies();

if (cookies != null) {
    for (Cookie cookie : cookies) {
        System.out.println(cookie.getName());
        System.out.println(cookie.getValue());
    }
}

Cookies are often used to store information such as session identities and preferences. Do not store sensitive data such as clear passwords directly in cookies; your identity credentials should also be combined with HttpOnly、Secure、SameSite and other security attributes and server verification mechanisms.

ServletContext application context

ServletContext Represents the running context of the current Web application. It is usually created when the application starts and destroyed when the application stops. There is usually only one for the same Web application ServletContext。

ServletContext context = getServletContext();
context.setAttribute("name", "abcde");
Object value = context.getAttribute("name");

Application-scope attributes can be shared by multiple servlets and multiple requests in the same Web application. Since it may be accessed by multiple threads at the same time, thread safety needs to be considered when saving variable shared data.

Comparison of common scopes

objecttypical rangecommon uses
HttpServletRequestone requestForward data and save current request processing results
HttpSessionOne client sessionLogin status, session-level user data
ServletContextEntire Web applicationApplication-level shared configuration or public data
CookieBrowser saves according to rulesSmall amount of data such as session identification and user preferences

Written by AI-rewritten

If you enjoyed this, leave a comment~

Loading...