Explain Query String and Query Parameter

Explain Query String and Query Parameter

Query String:

A query string is a part of the URL that contains data to be sent to the server. It is appended to the end of a URL after a question mark (`?`). The query string typically consists of key-value pairs separated by `&`.

Usage: Used to pass data to the server as part of the URL. Commonly used for filtering, sorting, or specifying search criteria in web applications.

Query Parameter

A query parameter is a single key-value pair within the query string. The key and value are separated by an equals sign (`=`). Multiple query parameters are separated by an ampersand (`&`).

Usage: Extracted from the query string and used to retrieve or process specific data. In Spring MVC, query parameters are often accessed using the `@RequestParam` annotation.

Query String and Query Parameter

Examples

Query String Example
1. Query String Example

Example URL: `http://example.com/products?category=electronics&priceRange=100-500`

- Query String: `category=electronics&priceRange=100-500`
  - This query string consists of two parameters: `category` and `priceRange`.
  

Query Parameter Example in Spring MVC
2. Query Parameter Example in Spring MVC
Example: Handling Query Parameters with `@RequestParam`

ProductController.java
```java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProductController {

    @GetMapping("/products")
    public String getProducts(@RequestParam(name = "category", defaultValue = "all") String category,
                              @RequestParam(name = "priceRange", required = false) String priceRange) {
        return "Category: " + category + ", Price Range: " + priceRange;
    }
}

Example URL: `http://example.com/products?category=electronics&priceRange=100-500`

In this example:

  • `@RequestParam(name = “category”, defaultValue = “all”)` extracts the `category` query parameter from the URL. If not provided, it defaults to `”all”`.
  • `@RequestParam(name = “priceRange”, required = false)` extracts the optional `priceRange` query parameter from the URL.

Summary of Query String and Query Parameter

  • Query String: The part of the URL that contains multiple key-value pairs separated by `&`, starting after the `?`.
  • Query Parameter: Individual key-value pairs within the query string, used to pass specific data to the server.

Homepage

Readmore