SpringBoot3.x入门到精通系列: 2.3 Web开发基础

SpringBoot 3.x Web开发基础

🌐 SpringBoot Web开发概述

SpringBoot提供了强大的Web开发支持,基于Spring MVC框架,可以快速构建RESTful API和传统的Web应用。

核心组件

  • DispatcherServlet: 前端控制器,处理所有HTTP请求
  • Controller: 控制器,处理具体的业务逻辑
  • ViewResolver: 视图解析器,解析视图名称
  • HandlerMapping: 处理器映射,将请求映射到处理器

🚀 快速开始

1. 添加Web依赖

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

这个starter包含了:

  • Spring MVC
  • 嵌入式Tomcat服务器
  • Jackson JSON处理
  • 数据验证支持

2. 创建第一个Controller

java 复制代码
package com.example.demo.controller;

import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/hello")
public class HelloController {
    
    @GetMapping
    public String hello() {
        return "Hello, SpringBoot 3.x Web!";
    }
    
    @GetMapping("/{name}")
    public Map<String, String> helloWithName(@PathVariable String name) {
        Map<String, String> response = new HashMap<>();
        response.put("message", "Hello, " + name + "!");
        response.put("timestamp", java.time.LocalDateTime.now().toString());
        return response;
    }
    
    @PostMapping
    public Map<String, Object> createGreeting(@RequestBody Map<String, String> request) {
        String name = request.getOrDefault("name", "World");
        Map<String, Object> response = new HashMap<>();
        response.put("greeting", "Hello, " + name + "!");
        response.put("status", "created");
        response.put("id", System.currentTimeMillis());
        return response;
    }
}

🎯 请求映射详解

1. HTTP方法映射

java 复制代码
@RestController
@RequestMapping("/api/users")
public class UserController {
    
    // GET请求 - 获取所有用户
    @GetMapping
    public List<User> getAllUsers() {
        return userService.findAll();
    }
    
    // GET请求 - 根据ID获取用户
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.findById(id);
    }
    
    // POST请求 - 创建用户
    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.save(user);
    }
    
    // PUT请求 - 更新用户
    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User user) {
        return userService.update(id, user);
    }
    
    // PATCH请求 - 部分更新用户
    @PatchMapping("/{id}")
    public User patchUser(@PathVariable Long id, @RequestBody Map<String, Object> updates) {
        return userService.patch(id, updates);
    }
    
    // DELETE请求 - 删除用户
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        userService.delete(id);
        return ResponseEntity.noContent().build();
    }
}

2. 请求参数处理

java 复制代码
@RestController
@RequestMapping("/api/search")
public class SearchController {
    
    // 查询参数
    @GetMapping("/users")
    public List<User> searchUsers(
            @RequestParam(required = false) String name,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "id") String sortBy) {
        
        return userService.search(name, page, size, sortBy);
    }
    
    // 多个查询参数
    @GetMapping("/products")
    public List<Product> searchProducts(
            @RequestParam Map<String, String> params) {
        
        return productService.search(params);
    }
    
    // 路径变量
    @GetMapping("/category/{categoryId}/products/{productId}")
    public Product getProduct(
            @PathVariable Long categoryId,
            @PathVariable Long productId) {
        
        return productService.findByCategoryAndId(categoryId, productId);
    }
    
    // 请求头
    @GetMapping("/profile")
    public UserProfile getUserProfile(
            @RequestHeader("Authorization") String token,
            @RequestHeader(value = "User-Agent", required = false) String userAgent) {
        
        return userService.getProfile(token, userAgent);
    }
}

3. 请求体处理

java 复制代码
@RestController
@RequestMapping("/api/orders")
public class OrderController {
    
    // JSON请求体
    @PostMapping
    public Order createOrder(@RequestBody @Valid OrderRequest request) {
        return orderService.create(request);
    }
    
    // 表单数据
    @PostMapping("/form")
    public Order createOrderFromForm(
            @RequestParam String customerName,
            @RequestParam String email,
            @RequestParam List<Long> productIds) {
        
        OrderRequest request = new OrderRequest(customerName, email, productIds);
        return orderService.create(request);
    }
    
    // 文件上传
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("description") String description) {
        
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("文件不能为空");
        }
        
        try {
            String fileName = fileService.store(file, description);
            return ResponseEntity.ok("文件上传成功: " + fileName);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("文件上传失败: " + e.getMessage());
        }
    }
}

📝 数据验证

1. 使用Bean Validation

java 复制代码
package com.example.demo.dto;

import jakarta.validation.constraints.*;
import java.time.LocalDate;

public class UserRequest {
    
    @NotBlank(message = "用户名不能为空")
    @Size(min = 2, max = 50, message = "用户名长度必须在2-50个字符之间")
    private String username;
    
    @NotBlank(message = "邮箱不能为空")
    @Email(message = "邮箱格式不正确")
    private String email;
    
    @NotNull(message = "年龄不能为空")
    @Min(value = 18, message = "年龄不能小于18岁")
    @Max(value = 100, message = "年龄不能大于100岁")
    private Integer age;
    
    @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
    private String phone;
    
    @Past(message = "生日必须是过去的日期")
    private LocalDate birthday;
    
    // 构造函数、getter和setter方法
    public UserRequest() {}
    
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }
    
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
    
    public Integer getAge() { return age; }
    public void setAge(Integer age) { this.age = age; }
    
    public String getPhone() { return phone; }
    public void setPhone(String phone) { this.phone = phone; }
    
    public LocalDate getBirthday() { return birthday; }
    public void setBirthday(LocalDate birthday) { this.birthday = birthday; }
}

🔗 下一篇

在下一篇文章中,我们将学习RESTful API的设计原则和最佳实践。


本文关键词: Web开发, Spring MVC, Controller, 请求映射, 数据验证, RESTful

相关推荐
wangbing11252 分钟前
ES6 (ES2015)新增的集合对象Set
前端·javascript·es6
nvd1119 分钟前
企业级 LLM 实战:在受限环境中基于 Copilot API 构建 ReAct MCP Agent
前端·copilot
Dragon Wu28 分钟前
TailWindCss cva+cn管理样式
前端·css
烤麻辣烫33 分钟前
Web开发概述
前端·javascript·css·vue.js·html
Front思43 分钟前
Vue3仿美团实现骑手路线规划
开发语言·前端·javascript
徐同保1 小时前
Nano Banana AI 绘画创作前端代码(使用claude code编写)
前端
Ulyanov1 小时前
PyVista与Tkinter桌面级3D可视化应用实战
开发语言·前端·python·3d·信息可视化·tkinter·gui开发
计算机程序设计小李同学1 小时前
基于Web和Android的漫画阅读平台
java·前端·vue.js·spring boot·后端·uniapp
lkbhua莱克瓦241 小时前
HTML与CSS核心概念详解
前端·笔记·html·javaweb
沛沛老爹1 小时前
从Web到AI:Agent Skills CI/CD流水线集成实战指南
java·前端·人工智能·ci/cd·架构·llama·rag