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

springboot创建请求处理

springboot创建请求处理

在这里插入图片描述

Spring Boot创建请求处理详细步骤

1. 创建Spring Boot项目

使用Spring Initializr创建基础项目:

  • 访问 https://start.spring.io
  • 选择:
    • Maven/Gradle
    • Java语言
    • Spring Boot版本(推荐3.x)
  • 添加依赖:
    Spring Web
    Spring Boot DevTools (可选)
    
2. 项目结构准备

创建标准目录:

src
├── main
│   ├── java
│   │   └── com.example.demo
│   │       ├── controller  // 控制器目录
│   │       ├── service     // 服务层目录
│   │       └── DemoApplication.java // 启动类
│   └── resources
│       └── application.properties
3. 创建控制器

controller包中创建请求处理类:

import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/api")
public class DemoController {// GET请求处理@GetMapping("/hello")public String hello() {return "Hello, Spring Boot!";}// POST请求处理@PostMapping("/user")public String createUser(@RequestBody User user) {return "User created: " + user.getName();}// 带路径参数的处理@GetMapping("/user/{id}")public String getUser(@PathVariable Long id) {return "User ID: " + id;}// 带查询参数的处理@GetMapping("/search")public String search(@RequestParam String keyword) {return "Searching for: " + keyword;}
}// DTO类
class User {private String name;private String email;// getters/setters
}
4. 配置请求参数处理

常见参数处理方式:

// 路径变量
@GetMapping("/product/{id}")
public String getProduct(@PathVariable("id") String productId) { ... }// 请求参数
@GetMapping("/filter")
public String filter(@RequestParam("category") String cat) { ... }// 请求体
@PostMapping("/save")
public ResponseEntity<?> saveData(@RequestBody DataDTO data) { ... }// 请求头
@GetMapping("/header")
public String getHeader(@RequestHeader("User-Agent") String agent) { ... }
5. 配置全局异常处理

创建异常处理器:

@ControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(Exception.class)public ResponseEntity<String> handleException(Exception e) {return ResponseEntity.status(500).body("Error: " + e.getMessage());}@ExceptionHandler(ResourceNotFoundException.class)@ResponseStatus(HttpStatus.NOT_FOUND)public ErrorResponse handleNotFound(ResourceNotFoundException ex) {return new ErrorResponse(ex.getMessage(), 404);}
}
6. 配置请求验证

在DTO中添加验证注解:

public class UserDTO {@NotBlank(message = "Name cannot be empty")private String name;@Email(message = "Invalid email format")private String email;
}

在控制器中启用验证:

@PostMapping("/register")
public ResponseEntity<?> registerUser(@Valid @RequestBody UserDTO user) {// 处理逻辑
}
7. 配置静态资源处理

application.properties中添加:

# 静态资源路径
spring.web.resources.static-locations=classpath:/static/# 文件上传限制
spring.servlet.multipart.max-file-size=10MB
8. 运行与测试
  1. 启动主类DemoApplication
  2. 测试接口:
    # GET测试
    curl http://localhost:8080/api/hello# POST测试
    curl -X POST -H "Content-Type: application/json" \
    -d '{"name":"John", "email":"john@example.com"}' \
    http://localhost:8080/api/user
    
9. 进阶配置

application.properties中添加常用配置:

# 修改端口
server.port=9090# 上下文路径
server.servlet.context-path=/demo# 开启HTTP/2
server.http2.enabled=true# 跨域配置
spring.mvc.cors.allowed-origins=*
10. 使用Swagger文档化

添加依赖:

<dependency><groupId>org.springdoc</groupId><artifactId>springdoc-openapi-starter-webmvc-ui</artifactId><version>2.3.0</version>
</dependency>

文章转载自:

http://VvZpIdiq.xgjhy.cn
http://toT4bOwT.xgjhy.cn
http://eahSNEEg.xgjhy.cn
http://c2FFanUG.xgjhy.cn
http://7cEdsiko.xgjhy.cn
http://41LeoXc1.xgjhy.cn
http://13R9Ub84.xgjhy.cn
http://O6YDsz4j.xgjhy.cn
http://KgZ3Q1Ud.xgjhy.cn
http://H32gXiBC.xgjhy.cn
http://Rqd1oaJW.xgjhy.cn
http://uWKVkobm.xgjhy.cn
http://lW5LTlXq.xgjhy.cn
http://AxVqgVOm.xgjhy.cn
http://e8zRxg2J.xgjhy.cn
http://8piD2tpQ.xgjhy.cn
http://Ag7YuHcd.xgjhy.cn
http://ncS0Bafv.xgjhy.cn
http://SdEMCzJ1.xgjhy.cn
http://YpyvxUGk.xgjhy.cn
http://SyuPEqNx.xgjhy.cn
http://BLG5lJF7.xgjhy.cn
http://LmXM1R3s.xgjhy.cn
http://cYJv074I.xgjhy.cn
http://hXuqcgzu.xgjhy.cn
http://N8YVzIYN.xgjhy.cn
http://8JzTYkt5.xgjhy.cn
http://goXg9reY.xgjhy.cn
http://MZlg47ym.xgjhy.cn
http://vdiu6pFQ.xgjhy.cn
http://www.dtcms.com/a/384337.html

相关文章:

  • 08-Redis 字符串类型全解析:从命令实操到业务场景落地
  • 学习海康VisionMaster之字符缺陷检测
  • CAD画图:002软件界面操作
  • 解锁全球业务潜能:AWS全球网络加速解决方案深度解析
  • HTTPS Everywhere 是什么?HTTPS 插件作用、iOS 抓包失败原因解析与常见抓包工具对比
  • 【C++】STL详解(七)—stack和queue的介绍及使用
  • 20250912在荣品RD-RK3588-MID开发板的Android13系统下拿掉卡迪屏的reset引脚的下拉复位波形
  • 在线图书借阅平台的设计与实现 —— 基于飞算JavaAI的实战开发全流程与优化实践
  • Git : 分支管理和远程仓库
  • 当传统金融遇上AI智能:AIStock系统深度技术解析
  • 大数据如何捕捉你的爱好?如何实现跨站用户行为分析?
  • 用OpenCV CSRT实现实时目标跟踪
  • 13.Linux OpenSSH 服务管理
  • 微算法科技(NASDAQ: MLGO)研发基于量子密钥图像的量子图像加密算法,提供更高安全性的图像保护方案
  • LAMP 环境部署
  • Java程序设计:Eclipse 安装和使用
  • ZooKeeper 集群高可用配置指南
  • 在天嵌 TQ3568 (Debian) 上配置并添加打印机教程
  • pcl封装10 get_area_form_boundary计算平面点云面积
  • 突破局域网限制:MongoDB远程管理新体验
  • C++学习:map/set源码剖析+利用红黑树封装map/set
  • HTML开发工具有哪些?常用HTML编辑器推荐、HTML开发工具对比与HTML调试工具实战应用
  • Redis篇章3:Redis 企业级缓存难题全解--预热、雪崩、击穿、穿透一网打尽
  • 什么区块链(Blockchain)?Rust的区块链的例子
  • LangChain4J-(5)-记忆缓存与持久化
  • 遇到 npm install报错 certificate has expired是因为淘宝镜像源(registry.npm.taobao.org)
  • Excel办公新选择:300项功能的免费插件
  • 在Excel和WPS表格中用照相机创建动态更新的数据图片
  • 开发与维护nodejs工具库或自定义npm包
  • 从企业实战中学习Appium自动化测试(一)