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. 运行与测试
- 启动主类
DemoApplication
- 测试接口:
# 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>