JavaWeb Fundamentals
JavaWeb encompasses the technology stack used to build web-based applications using the Java programming language. The standard architecture for these applications is the Browser/Server (B/S) model. In this paradigm, the client requires only a web browser, while all application logic and data storage are maintained on the server side. The browser sends requests for Web resources, and the server responds with the necessary data. This architecture simplifies maintenance and updates, as server-side changes are immediately available to clients without requiring software deployment on user devices.
The technology stack is typically divided into:
- Static Resources: Files such as HTML, CSS, JavaScript, and images that handle the presentation layer.
- Dynamic Resources: Components like Servlets and JSPs that process business logic.
- Database: The persistent storage layer.
- Web Server: Software that parses HTTP protocols and manages communication between the client and the application.
HTTP Protocol Details
The Hypertext Transfer Protocol (HTTP) defines the standard rules for data transfer between clients and servers.
Key Characteristics
- TCP-Based: Relies on TCP/IP for secure, connection-oriented communication.
- Request-Response Model: Communication is initiated by the client and answered by the server.
- Stateless: The protocol does not retain memory of previous transactions. Each request is independent, which improves speed but requires state management solutions like Cookies or Sessions for multi-step workflows.
Request Structure
An HTTP request consists of three main components:
- Request Line: Contains the HTTP method (e.g., GET, POST), the request URI, and the protocol version.
- Request Headers: Key-value pairs providing metadata (e.g.,
Host,User-Agent,Accept). - Request Body: Contains data sent by the client, primarily used in POST requests.
GET vs. POST
- GET: Parameters are appended to the URL in the request line. Suitable for retrieving data, but has length limitations.
- POST: Parameters are included in the request body. Ideal for sending large amounts of data or sensitive information.
Response Structure
The server response includes:
- Status Line: Protocol version, status code (e.g., 200 for OK, 404 for Not Found), and a status description.
- Response Headers: Metadata such as
Content-Type,Content-Length, and caching directives. - Response Body: The actual content (HTML, JSON, image data) returned to the client.
Apache Tomcat
Tomcat is a core project of the Apache Software Foundation, serving as a lightweight, open-source web server. It functions as a Servlet container, implementing specific Java EE specifications (Servlet, JSP). Tomcat parses HTTP requests and manages the lifecycle of Java web components.
Basic Operations
- Installation: Tomcat is distributed as a compressed archive; simply extract it to install.
- Execution: Run
bin/startup.bat(Windows) orbin/startup.sh(Linux) to start. Runbin/shutdown.bator press Ctrl+C to stop. - Configuration: Port settings are defined in
conf/server.xml. The default HTTP port is 8080.
Deployment
Web applications are typically packaged as WAR (Web Application Archive) files. Placing a WAR file into the webapps directory triggers automatic deployment. In integrated development environments (IDEs) like IntelliJ IDEA, Tomcat can be configured to run exploded directories or WAR artifacts directly.
Nginx Web Server
Nginx is a high-performance web server and reverse proxy known for its stability, low memory footprint, and high concurrency capabilities. It is often used to serve static content and as a load balancer for backend applications.
Installation and Commands
On Linux systems, installation involves downloading the source and compiling dependencies like PCRE and OpenSSL. Key commands include checking the configuration syntax (./nginx -t), starting the service (./nginx), and reloading the configuration (./nginx -s reload).
Configuration Structure
The nginx.conf file is hierarchical:
- Global Block: Settings affecting the entire server.
- Events Block: Network connection handling.
- HTTP Block: Contains
serverblocks for virtual hosts.
Use Cases
1. Static Resource Hosting
server {
listen 80;
server_name localhost;
location / {
root /usr/local/nginx/html;
index index.html index.htm;
}
}
2. Reverse Proxy
Nginx can forward client requests to a backend application server, abstracting the server's actual location.
server {
listen 80;
server_name example.com;
location /api/ {
proxy_pass http://192.168.1.10:8080;
}
}
3. Load Balancing
Using the upstream directive, Nginx distributes traffic across multiple servers to ensure high availability.
upstream backend_cluster {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend_cluster;
}
}
Decoupled Frontend and Backend Architecture
Overview
Modern development often employs a decoupled architecture where frontend and backend teams work independently. Frontend developers focus on user interfaces using technologies like HTML, CSS, Vue.js, or Node.js. Backend developers focus on APIs, databases, and business logic using Java or other languages. This separation improves development efficiency and allows for parallel progress.
API Management
Since the two sides are decoupled, the Application Programming Interface (API) becomes the contract between them. Tools like YApi are used to define and document these interfaces, ensuring both teams agree on request paths, parameters, and response formats.
Documentation with Swagger and Knife4j
Swagger allows for automatic generation of API documentation based on code annotations. Knife4j is an enhanced solution for integrating Swagger into Spring Boot projects.
Implementation Steps
- Add Dependency: Include
knife4j-spring-boot-starterin the project. - Configuration Class: Create a configuration bean to define the API grouping and metadata.
@Configuration
@EnableSwagger2
@EnableKnife4j
public class ApiConfig extends WebMvcConfigurationSupport {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder()
.title("Project API Documentation")
.version("2.0")
.description("Backend Interface Docs")
.build())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.project.controller"))
.paths(PathSelectors.any())
.build();
}
}
- Resource Mapping: Ensure static resources for Swagger UI are accessible in the Web MVC configuration.
Production Deployment
In a production environment, the architecture typically involves:
- Server A (Nginx): Hosts the static frontend files (built as a dist folder). It is configured to serve the frontend and proxy requests prefixed with
/apito the backend server. - Server B (Application): Runs the Java application (JAR) with an embedded Tomcat, connecting to the database and Redis.
Nginx Configuration Example:
server {
listen 80;
server_name www.example.com;
# Serve Frontend Static Files
location / {
root /usr/local/nginx/html/dist;
index index.html;
}
# Proxy Backend API Requests
location ^~ /api/ {
rewrite ^/api/(.*)$ /$1 break;
proxy_pass http://192.168.1.20:8080;
}
}