Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Handling Request Parameters in Spring Boot REST APIs

Tech 1

Project Structure Setup

When creating a Spring Boot web project, ensure the main application class and all controller are located in the same package or subpackages that fall within the component scan scope.

MainApplication
└── controller/
    └── UserController.java

Simple Parameters

Simple query parameters can be accessed directly by matching method argument names with parameter keys.

@RestController
public class UserController {
    
    @RequestMapping("/simpleParam")
    public String simpleParam(String username, Integer userAge) {
        System.out.println(username + " : " + userAge);
        return "OK";
    }
}

Access this endpoint via Postman using ?username=John&userAge=25 as query parameters.

POJO (Plain Old Java Object) Parameters

Create a models package to store entity classes. These classes require private fields with corresponding getter and setter methods.

package com.example.demo.models;

public class User {
    private String username;
    private Integer userAge;
    private Address residence;
    
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }
    
    public Integer getUserAge() { return userAge; }
    public void setUserAge(Integer userAge) { this.userAge = userAge; }
    
    public Address getResidence() { return residence; }
    public void setResidence(Address residence) { this.residence = residence; }
}
package com.example.demo.models;
public class Address {
    private String city;
    private String province;
}
@RestController
public class UserController {
    
    @RequestMapping("/userInfo")
    public String userInfo(User user) {
        System.out.println(user);
        return "OK";
    }
}

Spring automatically maps nested properties using dot notation: username, userAge, residence.city, residence.province.

Array and Collection Parameters

Array Handling

@RequestMapping("/interests")
public String interests(String[] hobbies) {
    System.out.println(Arrays.toString(hobbies));
    return "ok";
}

List Handling

@RequestMapping("/hobbyList")
public String hobbyList(@RequestParam List<String> interests) {
    System.out.println(interests);
    return "ok";
}
}

The @RequestParam annotation is required when binding multiple request parameter values into a List. Without it, Spring will throw a missing parameter error.

Date Parameters

@RequestMapping("/timestamp")
public String timestamp(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime lastModified) {
    System.out.println(lastModified);
    return "ok";
}

Input must strictly folow the defined pattern. For example: 2024-01-15 14:30:00

JSON Request Body

@RequestMapping(value = "/createUser", consumes = "application/json")
public String createUser(@RequestBody User user) {
    System.out.println(user);
    return "ok";
}

In Postman, select the raw body type with JSON format:

{
    "username": "Alice",
    "userAge": 30,
    "residence": {
        "city": "Shanghai",
        "province": "Shanghai"
    }
}

The @RequestBody annotasion deserializes the JSON payload into the specified Java object. Property keys must exactly match field names.

Path Variables

@RequestMapping("/details/{userId}/{username}")
public String getDetails(@PathVariable Integer userId, @PathVariable String username) {
    System.out.println(userId + " " + username);
    return "ok";
}

Each path variable requires its own @PathVariable annotation. The URL structure becomes /details/100/Alice.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.