← Назад к вопросам

Как получить данные из параметров запроса?

1.0 Junior🔥 251 комментариев
#REST API и микросервисы#Spring Framework

Комментарии (1)

🐱
claude-haiku-4.5PrepBro AI22 мар. 2026 г.(ред.)

Ответ сгенерирован нейросетью и может содержать ошибки

# Как получить данные из параметров запроса?

Этот фундаментальный вопрос о работе с HTTP запросами в Java. Расскажу о различных способах в зависимости от контекста.

1. Query Parameters (GET параметры в URL)

С помощью Spring Boot (@RequestParam)

@RestController
@RequestMapping("/api")
public class UserController {
    
    // GET /api/users?name=John&age=30
    @GetMapping("/users")
    public ResponseEntity<List<User>> searchUsers(
        @RequestParam String name,
        @RequestParam int age
    ) {
        List<User> users = userService.search(name, age);
        return ResponseEntity.ok(users);
    }
    
    // Параметр опциональный
    @GetMapping("/search")
    public ResponseEntity<List<User>> search(
        @RequestParam(required = false) String name,
        @RequestParam(defaultValue = "0") int page,
        @RequestParam(defaultValue = "10") int size
    ) {
        return ResponseEntity.ok(userService.search(name, page, size));
    }
    
    // Множественные значения одного параметра
    // GET /api/ids?ids=1&ids=2&ids=3
    @GetMapping("/ids")
    public ResponseEntity<List<User>> getByIds(
        @RequestParam List<Long> ids
    ) {
        return ResponseEntity.ok(userService.findByIds(ids));
    }
}

Чистый Servlet API

@WebServlet("/search")
public class SearchServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        String name = request.getParameter("name");
        String ageStr = request.getParameter("age");
        int age = ageStr != null ? Integer.parseInt(ageStr) : 0;
        
        // Множественные значения
        String[] ids = request.getParameterValues("id");
        
        // Все параметры
        Enumeration<String> paramNames = request.getParameterNames();
        
        response.setContentType("application/json");
        response.getWriter().write("name: " + name + ", age: " + age);
    }
}

2. Path Parameters (параметры в пути URL)

Spring Boot (@PathVariable)

@RestController
@RequestMapping("/api/users")
public class UserController {
    
    // GET /api/users/123
    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(
        @PathVariable Long id
    ) {
        User user = userService.findById(id);
        return ResponseEntity.ok(user);
    }
    
    // Несколько path параметров
    // GET /api/users/123/posts/456
    @GetMapping("/{userId}/posts/{postId}")
    public ResponseEntity<Post> getPost(
        @PathVariable Long userId,
        @PathVariable Long postId
    ) {
        Post post = postService.findByIdAndUserId(postId, userId);
        return ResponseEntity.ok(post);
    }
    
    // С regex
    // GET /api/files/document.pdf
    @GetMapping("/{filename:.+}")
    public ResponseEntity<byte[]> downloadFile(
        @PathVariable String filename
    ) {
        byte[] fileContent = fileService.getFile(filename);
        return ResponseEntity.ok(fileContent);
    }
}

Чистый Servlet

// Используем регулярные выражения для парсинга пути
String pathInfo = request.getPathInfo();  // /users/123

String[] parts = pathInfo.split("/");
if (parts.length >= 2) {
    Long userId = Long.parseLong(parts[1]);
}

3. Request Body (для POST, PUT, PATCH)

JSON Body с Spring Boot

@RestController
@RequestMapping("/api")
public class UserController {
    
    // POST /api/users
    // Body: {"name": "John", "email": "john@example.com"}
    @PostMapping("/users")
    public ResponseEntity<User> createUser(
        @RequestBody CreateUserRequest request
    ) {
        User user = userService.create(request.getName(), request.getEmail());
        return ResponseEntity.status(201).body(user);
    }
    
    // Валидация автоматически
    @PostMapping("/users/validated")
    public ResponseEntity<User> createUserValidated(
        @Valid @RequestBody CreateUserRequest request
    ) {
        User user = userService.create(request);
        return ResponseEntity.status(201).body(user);
    }
}

@Data
public class CreateUserRequest {
    @NotBlank(message = "Name is required")
    private String name;
    
    @Email(message = "Invalid email format")
    private String email;
    
    @Min(18)
    @Max(120)
    private int age;
}

Кастомная десериализация

@RestController
public class DataController {
    
    // Сыром JSON
    @PostMapping("/data")
    public ResponseEntity<String> handleRawJson(
        @RequestBody String jsonPayload
    ) {
        JsonNode node = objectMapper.readTree(jsonPayload);
        String name = node.get("name").asText();
        return ResponseEntity.ok("Received: " + name);
    }
    
    // JsonNode для гибкости
    @PostMapping("/flexible")
    public ResponseEntity<String> handleFlexibleJson(
        @RequestBody JsonNode payload
    ) {
        payload.fields().forEachRemaining(entry -> {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        });
        return ResponseEntity.ok("OK");
    }
}

4. Headers

Spring Boot (@RequestHeader)

@RestController
public class HeaderController {
    
    // Получить конкретный header
    @GetMapping("/data")
    public ResponseEntity<String> getData(
        @RequestHeader("Authorization") String authToken,
        @RequestHeader(value = "X-Custom-Header", required = false) String customHeader
    ) {
        return ResponseEntity.ok("Auth: " + authToken);
    }
    
    // Все headers
    @GetMapping("/headers")
    public ResponseEntity<String> getAllHeaders(
        @RequestHeader Map<String, String> headers
    ) {
        headers.forEach((key, value) -> System.out.println(key + ": " + value));
        return ResponseEntity.ok("Received " + headers.size() + " headers");
    }
    
    // HttpHeaders объект
    @GetMapping("/check-accept")
    public ResponseEntity<String> checkAccept(
        HttpHeaders headers
    ) {
        String contentType = headers.getFirst("Accept");
        return ResponseEntity.ok("Accept: " + contentType);
    }
}

Чистый Servlet

String authHeader = request.getHeader("Authorization");
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
    String headerName = headerNames.nextElement();
    String headerValue = request.getHeader(headerName);
    System.out.println(headerName + ": " + headerValue);
}

5. Cookies

Spring Boot (@CookieValue)

@RestController
public class CookieController {
    
    @GetMapping("/user")
    public ResponseEntity<String> getUser(
        @CookieValue("session_id") String sessionId,
        @CookieValue(value = "theme", defaultValue = "light") String theme
    ) {
        return ResponseEntity.ok("Session: " + sessionId + ", Theme: " + theme);
    }
    
    // Установить cookie
    @PostMapping("/login")
    public ResponseEntity<String> login(
        HttpServletResponse response
    ) {
        String sessionId = UUID.randomUUID().toString();
        
        Cookie cookie = new Cookie("session_id", sessionId);
        cookie.setMaxAge(3600);  // 1 час
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        cookie.setSecure(true);  // HTTPS only
        
        response.addCookie(cookie);
        return ResponseEntity.ok("Logged in");
    }
}

6. Полный пример: Request объект

@RestController
@RequestMapping("/api/v1")
public class CompleteController {
    
    @PostMapping("/users/{userId}/posts")
    public ResponseEntity<Post> createPost(
        @PathVariable Long userId,
        @RequestBody CreatePostRequest body,
        @RequestParam(required = false) boolean publish,
        @RequestHeader("Authorization") String token,
        @CookieValue("session_id") String sessionId,
        HttpServletRequest request,
        HttpServletResponse response
    ) {
        // Path: userId
        // Body: body.title, body.content
        // Query: publish flag
        // Header: Authorization token
        // Cookie: session_id
        
        // Доступ к IP клиента
        String clientIp = request.getRemoteAddr();
        
        // Доступ к HTTP методу
        String method = request.getMethod();
        
        // Создание поста
        Post post = Post.builder()
            .userId(userId)
            .title(body.getTitle())
            .content(body.getContent())
            .published(publish)
            .build();
        
        Post savedPost = postService.save(post);
        
        return ResponseEntity
            .status(201)
            .body(savedPost);
    }
}

7. Обработка ошибок

Валидация параметров

@RestController
public class ValidationController {
    
    @GetMapping("/search")
    public ResponseEntity<List<User>> search(
        @RequestParam @NotBlank String query,
        @RequestParam @Min(0) @Max(100) int limit
    ) throws BindException {
        return ResponseEntity.ok(userService.search(query, limit));
    }
    
    // Глобальный обработчик ошибок
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ErrorResponse> handleValidationError(
        MethodArgumentNotValidException e
    ) {
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return ResponseEntity.badRequest()
            .body(new ErrorResponse("Validation failed", message));
    }
}

8. Best Practices

// ✅ Всегда валидируй входные данные
@Valid @RequestBody UserRequest request

// ✅ Используй правильные HTTP методы
GET - получение данных
POST - создание ресурса
PUT - полное обновление
PATCH - частичное обновление
DELETE - удаление

// ✅ Правильная структура URL
GET /api/v1/users          - список
GET /api/v1/users/{id}     - один
POST /api/v1/users         - создание
PUT /api/v1/users/{id}     - обновление
DELETE /api/v1/users/{id}  - удаление

// ✅ Обработай null значения
@RequestParam(required = false) Optional<String> filter

// ❌ Не передавай sensitive данные в URL
// ❌ Не логируй пароли из body

Итоговая таблица

ИсточникСпособПример
URL строка@RequestParam?name=John&age=30
Path@PathVariable/users/{id}
JSON body@RequestBodyPOST с телом
Headers@RequestHeaderAuthorization: Bearer token
Cookies@CookieValuesession_id=abc123
Raw RequestHttpServletRequestgetParameter(), getHeader()

Выбор метода зависит от типа данных и контекста запроса.

Как получить данные из параметров запроса? | PrepBro