Java Web开发技术解析:从基础到实践的全栈指南

生态兼容性:支持从传统单体应用到现代微服务的平滑演进。

二、核心技术组件深度解析(实践篇)

2.1 动态Web技术

2.1.1 Servlet核心机制

public class OrderServlet extends HttpServlet {

private OrderService service = new OrderService();

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

// 请求参数处理

String productId = req.getParameter("productId");

int quantity = Integer.parseInt(req.getParameter("quantity"));

// 业务逻辑执行

try {

Order order = service.createOrder(productId, quantity);

// 响应处理

resp.setContentType("application/json");

resp.setCharacterEncoding("UTF-8");

resp.getWriter().write(new ObjectMapper().writeValueAsString(order));

} catch (InventoryException e) {

resp.sendError(HttpServletResponse.SC_CONFLICT, e.getMessage());

}

}

}

Servlet生命周期详解:

初始化阶段:Web容器加载Servlet类并调用init()方法,常用于资源初始化

服务阶段:

每个请求创建独立线程

调用service()方法路由到doGet()/doPost()等具体方法

销毁阶段:调用destroy()释放数据库连接等资源

请求处理核心对象:

HttpServletRequest:

// 获取多值参数

String[] interests = request.getParameterValues("interest");

// 读取JSON body

BufferedReader reader = request.getReader();

StringBuilder jsonBody = new StringBuilder();

String line;

while ((line = reader.readLine()) != null) {

jsonBody.append(line);

}

HttpServletResponse:

// 设置缓存控制头

response.setHeader("Cache-Control", "no-cache, max-age=0");

// 发送重定向

response.sendRedirect("/success.jsp");

// 设置Cookie

Cookie sessionCookie = new Cookie("JSESSIONID", sessionId);

sessionCookie.setHttpOnly(true);

response.addCookie(sessionCookie);

2.1.2 JSP技术演进

<%@ page import="com.example.models.Product" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

Product List

商品清单

名称 价格 库存
${product.name} ¥

有货

缺货

JSP九大内置对象:

对象

类型

作用域

request

HttpServletRequest

Request

response

HttpServletResponse

Page

session

HttpSession

Session

application

ServletContext

Application

out

JspWriter

Page

config

ServletConfig

Page

pageContext

PageContext

Page

page

Object

Page

exception

Throwable

Page

JSP编译过程:

翻译阶段:将JSP文件转换为Servlet.java

编译阶段:使用Jasper编译器生成.class文件

类加载阶段:由类加载器加载到JVM

执行阶段:调用_jspService()方法处理请求

2.2 数据持久化方案

2.2.1 JDBC高级应用

public class JdbcUtil {

private static DataSource dataSource;

static {

HikariConfig config = new HikariConfig();

config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");

config.setUsername("root");

config.setPassword("password");

config.addDataSourceProperty("cachePrepStmts", "true");

config.addDataSourceProperty("prepStmtCacheSize", "250");

config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");

dataSource = new HikariDataSource(config);

}

public static Connection getConnection() throws SQLException {

return dataSource.getConnection();

}

public static void executeTransaction(Consumer task) {

try (Connection conn = getConnection()) {

try {

conn.setAutoCommit(false);

task.accept(conn);

conn.commit();

} catch (SQLException e) {

conn.rollback();

throw e;

}

}

}

}

2.2.2 ORM框架对比

Hibernate核心配置:

com.mysql.cj.jdbc.Driver

jdbc:mysql://localhost:3306/mydb

root

password

org.hibernate.dialect.MySQL8Dialect

true

update

MyBatis动态SQL示例:

2.3 架构设计模式

2.3.1 MVC模式实现

// Controller

@WebServlet("/products")

public class ProductController extends HttpServlet {

private ProductService service = new ProductService();

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) {

String action = req.getParameter("action");

if ("detail".equals(action)) {

Long id = Long.parseLong(req.getParameter("id"));

Product product = service.getProduct(id);

req.setAttribute("product", product);

req.getRequestDispatcher("/productDetail.jsp").forward(req, resp);

} else {

List products = service.getAllProducts();

req.setAttribute("products", products);

req.getRequestDispatcher("/productList.jsp").forward(req, resp);

}

}

}

// Service

public class ProductService {

private ProductDao dao = new ProductDao();

public Product getProduct(Long id) {

return dao.findById(id);

}

public List getAllProducts() {

return dao.findAll();

}

}

// DAO

public class ProductDao {

public Product findById(Long id) {

// JDBC或ORM实现

}

}

2.3.2 RESTful API设计规范

HATEOAS示例:

@GetMapping("/{id}")

public ResponseEntity> getProduct(@PathVariable Long id) {

Product product = service.findById(id);

Link selfLink = linkTo(methodOn(ProductController.class)

.getProduct(id)).withSelfRel();

Link ordersLink = linkTo(methodOn(OrderController.class)

.getProductOrders(id)).withRel("orders");

Resource resource = new Resource<>(product);

resource.add(selfLink, ordersLink);

return ResponseEntity.ok(resource);

}

版本控制策略:

URI版本控制

GET /api/v1/products/123

Header版本控制

GET /api/products/123

Accept: application/vnd.example.v1+json

参数版本控制

GET /api/products/123?version=1

三、开发工具链深度优化

3.1 集成开发环境

IntelliJ IDEA高级功能:

数据库工具:直接执行SQL、可视化表结构

HTTP客户端:创建.http文件测试API

GET http://localhost:8080/api/products

Accept: application/json

###

POST http://localhost:8080/api/orders

Content-Type: application/json

{

"productId": 123,

"quantity": 2

}

代码检查:识别N+1查询问题、循环依赖等

Eclipse插件体系:

Spring Tools Suite:可视化Bean依赖关系

MyBatis Editor:XML映射文件智能提示

Checkstyle:代码规范检查

四、企业级应用实战演练

4.1 电商订单系统设计

领域模型:

public class Order {

private Long id;

private OrderStatus status;

private List items;

private BigDecimal totalAmount;

private LocalDateTime createTime;

public void addItem(Product product, int quantity) {

items.add(new OrderItem(product, quantity));

totalAmount = totalAmount.add(product.getPrice().multiply(new BigDecimal(quantity)));

}

public void cancel() {

if (status != OrderStatus.PENDING) {

throw new IllegalStateException("只能取消待处理订单");

}

status = OrderStatus.CANCELLED;

}

}

public enum OrderStatus {

PENDING, PAID, SHIPPED, COMPLETED, CANCELLED

}

分布式事务处理:

@Transactional

public void placeOrder(OrderRequest request) {

// 扣减库存

inventoryService.deductStock(request.getSku(), request.getQuantity());

// 创建订单

Order order = orderService.create(request);

// 发送领域事件

applicationEventPublisher.publishEvent(new OrderCreatedEvent(order));

}

@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)

public void handleOrderCreatedEvent(OrderCreatedEvent event) {

paymentService.createPayment(event.getOrder());

notificationService.sendConfirmation(event.getOrder());

}

4.2 高并发场景优化

缓存策略实现:

@Cacheable(value = "products", key = "#id", unless = "#result == null")

public Product getProduct(Long id) {

return productDao.findById(id);

}

@CacheEvict(value = "products", key = "#product.id")

public void updateProduct(Product product) {

productDao.update(product);

}

@Caching(

evict = {

@CacheEvict(value = "products", key = "#product.id"),

@CacheEvict(value = "productList", allEntries = true)

}

)

public void updateWithCacheClear(Product product) {

productDao.update(product);

}

数据库分库分表:

@Configuration

public class ShardingConfig {

@Bean

public DataSource dataSource() throws SQLException {

Map dataSourceMap = new HashMap<>();

dataSourceMap.put("ds0", createDataSource("ds0"));

dataSourceMap.put("ds1", createDataSource("ds1"));

ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();

shardingRuleConfig.getTableRuleConfigs().add(getOrderTableRule());

return ShardingDataSourceFactory.createDataSource(

dataSourceMap, shardingRuleConfig, new Properties());

}

private TableRuleConfiguration getOrderTableRule() {

TableRuleConfiguration result = new TableRuleConfiguration("orders", "ds${0..1}.orders_${0..15}");

result.setDatabaseShardingStrategyConfig(

new InlineShardingStrategyConfiguration("user_id", "ds${user_id % 2}"));

result.setTableShardingStrategyConfig(

new StandardShardingStrategyConfiguration("id", new ModuloShardingTableAlgorithm()));

return result;

}

}