Spring Boot Interview Questions

25 Questions
Spring Boot

Spring Boot

Java

Java

BackendWeb Development

Question 13

What is the purpose of the @PathVariable and @RequestParam annotations?

Answer:

The @PathVariable and @RequestParam annotations in Spring MVC are used to extract values from the URL in HTTP requests. They serve different purposes and are used in different contexts within a Spring controller.

@PathVariable

The @PathVariable annotation is used to extract values from the URI path. It is commonly used when you need to handle dynamic URLs and map the segments of the URL directly to method parameters.

Purpose:

  • Extracts a value from a URI template.
  • Maps URI template variables to method parameters in a controller.

Example:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @GetMapping("/users/{id}")
    public User getUserById(@PathVariable("id") Long userId) {
        // Logic to retrieve user by ID
        return userService.findById(userId);
    }
}

In this example:

  • The URL /users/{id} contains a variable part {id}.
  • The @PathVariable("id") annotation maps this variable to the userId parameter of the getUserById method.

@RequestParam

The @RequestParam annotation is used to extract query parameters from the URL. Query parameters are typically used for filtering, sorting, or other types of refinement of a request.

Purpose:

  • Extracts a value from a query parameter in the URL.
  • Maps query parameters to method parameters in a controller.

Example:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class ProductController {

    @GetMapping("/products")
    public List<Product> getProducts(@RequestParam(value = "category", required = false) String category,
                                     @RequestParam(value = "price", required = false) Double price) {
        // Logic to retrieve products based on query parameters
        return productService.findProducts(category, price);
    }
}

In this example:

  • The URL /products can have query parameters like ?category=electronics&price=1000.
  • The @RequestParam("category") annotation maps the category query parameter to the category method parameter.
  • The required = false attribute makes the query parameter optional.

Comparison and Use Cases

  • @PathVariable:

    • Used for extracting data from the URI path.
    • Ideal for RESTful APIs where the path itself contains the information (e.g., resource identifiers).
    • Example: /users/{id}, /orders/{orderId}.
  • @RequestParam:

    • Used for extracting query parameters from the URL.
    • Ideal for filtering, sorting, or specifying optional parameters in a request.
    • Example: /products?category=electronics&price=1000, /search?q=spring+boot.

Detailed Examples

Using @PathVariable

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class OrderController {

    @GetMapping("/orders/{orderId}")
    public Order getOrder(@PathVariable("orderId") Long orderId) {
        // Logic to retrieve order by ID
        return orderService.findById(orderId);
    }

    @GetMapping("/orders/{orderId}/items/{itemId}")
    public OrderItem getOrderItem(@PathVariable("orderId") Long orderId,
                                  @PathVariable("itemId") Long itemId) {
        // Logic to retrieve a specific item from an order
        return orderService.findItemById(orderId, itemId);
    }
}

Using @RequestParam

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class SearchController {

    @GetMapping("/search")
    public List<Result> search(@RequestParam("q") String query,
                               @RequestParam(value = "sort", defaultValue = "asc") String sort) {
        // Logic to perform search with query and sort parameters
        return searchService.search(query, sort);
    }

    @GetMapping("/filter")
    public List<Item> filterItems(@RequestParam(value = "category", required = false) String category,
                                  @RequestParam(value = "price", required = false) Double price) {
        // Logic to filter items based on category and price
        return itemService.filterItems(category, price);
    }
}

Summary

  • @PathVariable:

    • Extracts values from URI path segments.
    • Useful for RESTful API design.
    • Maps URI template variables directly to method parameters.
    • Example usage: /users/{id}, /orders/{orderId}/items/{itemId}.
  • @RequestParam:

    • Extracts values from query parameters in the URL.
    • Useful for passing optional parameters and filtering.
    • Maps query parameters to method parameters.
    • Example usage: /products?category=electronics&price=1000, /search?q=keyword&sort=asc.

By using @PathVariable and @RequestParam appropriately, you can design clean and efficient RESTful APIs that handle URL paths and query parameters effectively.

Recent job openings