Web basics

Published 2026-07-29 10:34 Updated 2026-07-29 10:34 1276 words 7 min read ... Page views

This paper systematically introduces the basic composition and development mode of Web application, including the division of front-end, back-end, database and server, and the advantages and disadvantages of front-end integration and separation. The responsibilities of View, Controller and Model layers in MVC layered architecture are emphasized, and the core components of Servlet API such as HttpServletRequest, HttpServletResponse, HttpSession, Cookie and ServletContext are explained in detail. The key practices such as request processing, session management, data sharing and security configuration are emphasized.

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.

  • Backend: 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: Contract the request address, request method, parameter format and response format to enable 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: handles 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 Servlet 4.0 projects based on the javax.servlet namespace:

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

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

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 HTTP requests sent by clients. After a request is processed, the request object is usually no longer used.

Common operations include:

  • Obtaining request method: request.getMethod().

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

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

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

  • Get a single request parameter: request.getParameter("参数名").

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

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

  • Read request range attribute: 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 is used to set status codes, response headers, character coding and response bodies.

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 is used to save data related to a client session on the server. When request.getSession() is first called, the container will usually create a new session if the current session does not exist.

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

Browsers usually carry session identifiers through session cookies, so that subsequent requests can 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 directly store sensitive data such as clear text passwords in cookies; identity credentials should also be combined with security attributes such as HttpOnly, Secure, and SameSite and server-side 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 ServletContext for the same Web application.

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 Purpose
HttpServletRequestrequestsonce to forward data and save the current request processing result
HttpSessionOne client sessionLogin status, session-level user data
ServletContextEntire Web applicationApplication-level shared configuration or public data
Cookiebrowser saves a small amount of data such assession ID and user preferences according to rules

If you enjoyed this, leave a comment~

... Page views
© 2026 跨越星轨的客 @Hoshiumi
Powered by theme astro-koharu · Inspired by Shoka