本文目录导读:

我来为你详细梳理Java Web请求接收的规范化流程,从客户端请求到服务端响应的完整链路。
整体流程概览
graph TD
A[客户端请求] --> B[网络层]
B --> C[Web服务器/容器]
C --> D[Servlet Filter链]
D --> E[DispatcherServlet]
E --> F[HandlerMapping]
F --> G[HandlerInterceptor前置]
G --> H[Controller处理]
H --> I[HandlerInterceptor后置]
I --> J[视图解析/响应处理]
J --> K[响应返回客户端]
各环节规范详解
请求入口层规范
1 HTTP请求规范
// 请求规范示例
@PostMapping("/api/users")
public ResponseEntity<UserResponse> createUser(
@Valid @RequestBody UserCreateRequest request,
@RequestHeader("Authorization") String token,
@RequestParam(defaultValue = "10") int pageSize
) {
// 处理逻辑
}
规范要求:
- 使用标准HTTP方法(GET/POST/PUT/DELETE)
- URL命名遵循RESTful规范
- 请求头包含必要认证信息
- 请求体使用JSON/XML标准格式
2 统一拦截器配置
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LogInterceptor())
.addPathPatterns("/api/**")
.order(1);
registry.addInterceptor(new AuthInterceptor())
.addPathPatterns("/api/**")
.excludePathPatterns("/api/auth/**", "/api/public/**")
.order(2);
}
}
请求参数接收规范
1 统一请求对象设计
// 通用请求封装
public class BaseRequest {
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime requestTime;
@NotEmpty(message = "请求ID不能为空")
private String requestId;
private String source; // 请求来源
}
// 业务请求继承
public class CreateUserRequest extends BaseRequest {
@NotBlank(message = "用户名不能为空")
@Size(min = 2, max = 50, message = "用户名长度2-50")
private String username;
@Email(message = "邮箱格式不正确")
private String email;
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
private String phone;
}
2 参数校验规范
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidationException(
MethodArgumentNotValidException ex) {
BindingResult bindingResult = ex.getBindingResult();
List<FieldError> fieldErrors = bindingResult.getFieldErrors();
String errorMessage = fieldErrors.stream()
.map(error -> error.getField() + ": " + error.getDefaultMessage())
.collect(Collectors.joining(", "));
return ResponseEntity.badRequest()
.body(new ErrorResponse("VALIDATION_ERROR", errorMessage));
}
}
请求处理层规范
1 控制器层规范
@RestController
@RequestMapping("/api/v1/users")
@RequiredArgsConstructor
public class UserController {
private final UserService userService;
@PostMapping
@PreAuthorize("hasRole('ADMIN')")
@Operation(summary = "创建用户", description = "创建新用户账号")
public ApiResponse<UserVO> createUser(@Valid @RequestBody CreateUserRequest request) {
// 记录请求日志
log.info("创建用户请求: {}", request);
// 业务处理
UserVO userVO = userService.createUser(request.toDTO());
// 返回统一响应
return ApiResponse.success(userVO);
}
}
2 服务层规范
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
@Override
public UserVO createUser(CreateUserDTO dto) {
// 参数校验
validateCreateUser(dto);
try {
// 业务逻辑
User user = new User();
BeanUtils.copyProperties(dto, user);
user.setPassword(passwordEncoder.encode(dto.getPassword()));
user.setStatus(UserStatus.ACTIVE);
// 持久化
user = userRepository.save(user);
// 发送事件
eventPublisher.publishEvent(new UserCreatedEvent(user));
return UserVO.fromEntity(user);
} catch (DataIntegrityViolationException e) {
throw new BusinessException(ErrorCode.USER_ALREADY_EXISTS);
}
}
}
响应处理规范
1 统一响应格式
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class ApiResponse<T> {
private int code;
private String message;
private T data;
private LocalDateTime timestamp;
private String requestId;
public static <T> ApiResponse<T> success(T data) {
return ApiResponse.<T>builder()
.code(200)
.message("success")
.data(data)
.timestamp(LocalDateTime.now())
.requestId(RequestIdHolder.get())
.build();
}
public static <T> ApiResponse<T> error(int code, String message) {
return ApiResponse.<T>builder()
.code(code)
.message(message)
.data(null)
.timestamp(LocalDateTime.now())
.requestId(RequestIdHolder.get())
.build();
}
}
2 异常处理规范
@RestControllerAdvice
public class GlobalExceptionHandler {
// 业务异常处理
@ExceptionHandler(BusinessException.class)
public ResponseEntity<ApiResponse<Void>> handleBusinessException(BusinessException ex) {
log.warn("业务异常: {}", ex.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(ApiResponse.error(ex.getCode(), ex.getMessage()));
}
// 系统异常处理
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiResponse<Void>> handleException(Exception ex) {
log.error("系统异常", ex);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ApiResponse.error(500, "系统繁忙,请稍后重试"));
}
}
安全规范
1 请求验证
@Component
public class RequestValidator {
public void validate(RequestContext context) {
// 1. 防重放攻击
checkReplayAttack(context);
// 2. 签名验证
verifySignature(context);
// 3. 权限验证
checkPermission(context);
// 4. 频率限制
checkRateLimit(context);
}
}
2 安全过滤器
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SecurityFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain)
throws ServletException, IOException {
// 1. 清理输入
String sanitizedInput = HtmlUtils.htmlEscape(request.getParameter("input"));
// 2. XSS防护
XssRequestWrapper xssRequest = new XssRequestWrapper(request);
// 3. SQL注入防护
SqlInjectionFilter.validate(xssRequest);
// 4. 设置安全响应头
response.setHeader("X-Content-Type-Options", "nosniff");
response.setHeader("X-Frame-Options", "DENY");
response.setHeader("X-XSS-Protection", "1; mode=block");
chain.doFilter(xssRequest, response);
}
}
性能监控规范
1 请求链路追踪
@Component
public class RequestTracingFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws IOException, ServletException {
// 生成追踪ID
String traceId = UUID.randomUUID().toString().replace("-", "");
MDC.put("traceId", traceId);
// 记录开始时间
long startTime = System.currentTimeMillis();
try {
chain.doFilter(request, response);
} finally {
// 记录请求耗时
long duration = System.currentTimeMillis() - startTime;
log.info("请求完成: method={}, uri={}, status={}, duration={}ms",
request.getMethod(),
request.getRequestURI(),
response.getStatus(),
duration);
// 清除上下文
MDC.clear();
}
}
}
日志记录规范
1 请求日志AOP
@Aspect
@Component
@Order(1)
public class RequestLogAspect {
@Around("@annotation(org.springframework.web.bind.annotation.RequestMapping) " +
"|| @annotation(org.springframework.web.bind.annotation.PostMapping)")
public Object logRequest(ProceedingJoinPoint joinPoint) throws Throwable {
// 获取请求参数
Object[] args = joinPoint.getArgs();
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
// 记录请求信息
log.info("请求方法: {}", signature.getMethod().getName());
log.info("请求参数: {}", maskSensitiveData(args));
// 执行请求
Object result = joinPoint.proceed();
// 记录响应
log.info("响应结果: {}", maskSensitiveData(result));
return result;
}
private Object maskSensitiveData(Object data) {
// 对密码、手机号等进行脱敏处理
// 省略具体实现
return data;
}
}
最佳实践清单
请求接收规范检查表
- [ ] 是否使用DTO接收请求参数?
- [ ] 是否添加了参数校验注解?
- [ ] 是否有全局异常处理器?
- [ ] 响应格式是否统一?
- [ ] 是否进行了输入过滤和转义?
- [ ] 是否添加了请求追踪ID?
- [ ] 是否记录了完整的请求日志?
- [ ] 是否设置了超时和限流?
- [ ] 是否有幂等性处理?
- [ ] 是否对敏感数据进行了脱敏?
常见问题处理
// 1. 大文件上传处理
@PostMapping("/upload")
public ResponseEntity<ApiResponse<String>> uploadFile(
@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return ResponseEntity.badRequest().body(ApiResponse.error(400, "文件不能为空"));
}
if (file.getSize() > MAX_FILE_SIZE) {
return ResponseEntity.badRequest().body(ApiResponse.error(400, "文件大小超出限制"));
}
// 处理文件
}
// 2. 异步请求处理
@PostMapping("/async-task")
public CompletableFuture<ResponseEntity<ApiResponse<String>>> asyncTask(
@RequestBody AsyncTaskRequest request) {
return CompletableFuture.supplyAsync(() -> {
// 异步处理逻辑
return ResponseEntity.ok(ApiResponse.success("任务已提交"));
});
}
遵循以上规范,可以构建出健壮、可维护、安全的Java请求接收处理系统,关键是要在项目初期就制定统一的规范,并通过code review确保贯彻执行。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播