当前位置: 首页 > news >正文

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依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>

这个starter包含了:

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

2. 创建第一个Controller

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 {@GetMappingpublic 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;}@PostMappingpublic 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方法映射

@RestController
@RequestMapping("/api/users")
public class UserController {// GET请求 - 获取所有用户@GetMappingpublic List<User> getAllUsers() {return userService.findAll();}// GET请求 - 根据ID获取用户@GetMapping("/{id}")public User getUserById(@PathVariable Long id) {return userService.findById(id);}// POST请求 - 创建用户@PostMappingpublic 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. 请求参数处理

@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. 请求体处理

@RestController
@RequestMapping("/api/orders")
public class OrderController {// JSON请求体@PostMappingpublic 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

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

http://www.dtcms.com/a/311837.html

相关文章:

  • sifu mod制作 相关经验
  • 11:java学习笔记:1D array(1维数组)
  • Windows下定位Mingw编译的Qt程序崩溃堆栈
  • Python科研数据可视化技术
  • 2025年常见网络安全问题及针对性预防措施
  • 小迪23年-22~27——php简单回顾(2)
  • pytorch的 Size[3] 和 Size[3,1] 区别
  • 动态规划Day7学习心得
  • 深入理解Linux线程:从概念到控制的最佳实践
  • jenkins从入门到精通-P1—九五小庞
  • Python编程基础与实践:Python函数编程入门
  • 基于Redis自动过期的流处理暂停机制
  • day38 力扣279.完全平方数 力扣322. 零钱兑换 力扣139.单词拆分
  • 位运算-371.两整数之和-力扣(LeetCode)
  • 2 安装 Docker 和 Jenkins:持续构建环境起步
  • Chisel芯片开发入门系列 -- 17. CPU芯片开发和解释7(5级流水线指令原理)
  • 洛谷 P3372 【模板】线段树 1-普及+/提高
  • 【AI学习】RadioDiff:代码学习
  • Paper Reading《TrafficFormer: An Efficient Pre-trained Model for Traffic Data》
  • 【MQ】kafka同步和异步的区别
  • Windows中使用Qwen模型:VSCode+Cline
  • 64GB U盘实际显示容量为57.2GB的原因解析
  • innoDB的buffer pool
  • Wasatch SoftRIP数码打印 印花软件
  • 谷歌开源Agent框架ADK快速入门
  • 深入理解 Go 语言中 Map 的底层原理
  • Python爬虫实战:研究SimpleCV技术,构建图像获取及处理系统
  • Apache Doris数据库——大数据技术
  • 【LeetCode刷题指南】--二叉树的前序遍历,二叉树的中序遍历
  • MCP Agent 工程框架Dify初探