Category: Spring Updated: Jul 30, 2026

Complete Guide to Spring @PathVariable for Java Beginners

Spring @PathVariable Annotation Tutorial for Beginners
Spring @PathVariable Annotation Tutorial for Beginners

Learn Through a Conversation Between a Teacher and a Student

Student

"Is there a way to get values directly from the URL in Spring Boot?"

Teacher

"Yes, in Spring Boot you can use the @PathVariable annotation to extract values from the URL path."

Student

"So I don’t need to use query parameters?"

Teacher

"Exactly. @PathVariable allows you to create clean and readable URLs."

Student

"Can you show me how to use it step by step?"

Teacher

"Of course. Let’s learn how to use @PathVariable in a simple and practical way!"

1. What is @PathVariable?

Key Takeaway: Let's dive into the core concepts of "1. What is @PathVariable?" cleanly and effectively.

1. What is @PathVariable?
1. What is @PathVariable?

The @PathVariable annotation in Spring Boot is used to extract values from the URL path. It is commonly used in REST APIs to make URLs more meaningful and user-friendly.

For example, instead of using a query string like /user?id=1, you can use a cleaner URL like /user/1. This approach is widely used in modern web applications and is important for Java beginners learning Spring Boot.

Understanding how to use @PathVariable is a key part of Java programming basics and Spring MVC development.

2. Basic Usage of @PathVariable

2. Basic Usage of @PathVariable
2. Basic Usage of @PathVariable

Let’s start with a simple example. In this case, we extract a value from the URL and return it as a response.


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("/user/{id}")
    public String getUser(@PathVariable int id) {
        return "User ID: " + id;
    }
}

In this example, the value inside the URL path is assigned to the variable id. This is one of the most common patterns in a Java tutorial for beginners.


User ID: 1

3. Using Multiple Path Variables

3. Using Multiple Path Variables
3. Using Multiple Path Variables

You can also use multiple values in the URL. This is useful when you need to pass more than one parameter.


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

@RestController
public class ProductController {

    @GetMapping("/product/{category}/{id}")
    public String getProduct(@PathVariable String category, @PathVariable int id) {
        return "Category: " + category + ", ID: " + id;
    }
}

This example shows how to handle multiple path variables in Spring Boot. It is commonly used in RESTful API design.


Category: book, ID: 10

4. Matching Variable Names

Key Takeaway: Let's dive into the core concepts of "4. Matching Variable Names" cleanly and effectively.

4. Matching Variable Names
4. Matching Variable Names

By default, the variable name in the method must match the name in the URL. However, you can explicitly define the name if needed.


@GetMapping("/order/{orderId}")
public String getOrder(@PathVariable("orderId") int id) {
    return "Order ID: " + id;
}

This is useful when your variable names are different from the URL parameters.


Order ID: 5

5. Using @PathVariable with Different Data Types

5. Using @PathVariable with Different Data Types
5. Using @PathVariable with Different Data Types

The @PathVariable annotation supports different data types such as int, long, and String. Spring automatically converts the value from the URL to the correct type.


@GetMapping("/price/{amount}")
public String getPrice(@PathVariable double amount) {
    return "Price: " + amount;
}

This makes it very flexible and easy to use in Java Spring Boot applications.


Price: 99.99

6. Difference Between @PathVariable and @RequestParam

6. Difference Between @PathVariable and @RequestParam
6. Difference Between @PathVariable and @RequestParam

Beginners often confuse @PathVariable with @RequestParam. Both are used to get values from a request, but they work differently.

  • @PathVariable is used for values in the URL path
  • @RequestParam is used for query parameters
  • @PathVariable creates cleaner URLs
  • @RequestParam is useful for optional values

Choosing the right one depends on your API design.

7. Common Use Cases in Real Applications

Key Takeaway: Let's dive into the core concepts of "7. Common Use Cases in Real Applications" cleanly and effectively.

7. Common Use Cases in Real Applications
7. Common Use Cases in Real Applications

In real-world Java Spring Boot projects, @PathVariable is used in many scenarios:

  • Fetching user data by ID
  • Accessing product details
  • Handling REST API endpoints
  • Building clean and SEO-friendly URLs

These use cases are essential for building modern web applications and RESTful services.

8. Best Practices for Beginners

8. Best Practices for Beginners
8. Best Practices for Beginners

When using @PathVariable in Spring Boot, keep these best practices in mind:

  • Use meaningful names for URL paths
  • Keep URLs simple and readable
  • Use proper data types
  • Combine with RESTful design principles

Following these tips will help you create better APIs and improve your Java programming skills.

Summary

Summary
Summary

The @PathVariable annotation in Spring Boot is a fundamental feature that every Java beginner should understand when learning how to build modern web applications. It allows developers to extract values directly from the URL path, making APIs cleaner, more readable, and easier to design. Instead of relying on query parameters, @PathVariable enables you to create RESTful URLs that clearly represent resources, such as users, products, or orders.

In a typical Java Spring Boot application, @PathVariable is used inside controller methods to bind URL segments to method parameters. This makes it possible to dynamically handle requests based on user input in the URL. For example, retrieving a specific user by ID or accessing product details by category and ID becomes simple and intuitive. This approach is widely used in real-world applications and is a key part of Java programming basics and REST API design.

One of the most important advantages of using @PathVariable is its ability to improve code readability and maintainability. Clean URLs are easier for both developers and users to understand. Additionally, Spring automatically handles type conversion, allowing you to directly map URL values to data types such as int, long, or String. This reduces boilerplate code and makes development more efficient, especially for beginners following a Java tutorial for beginners.

Understanding the difference between @PathVariable and @RequestParam is also essential. While @PathVariable is used for values embedded in the URL path, @RequestParam is used for query parameters. Choosing the right approach depends on the design of your API. In general, @PathVariable is preferred for identifying resources, while @RequestParam is better for optional filters or search conditions.

In real-world Java Spring Boot projects, @PathVariable is commonly used in RESTful APIs to handle resource-based routing. It works seamlessly with controllers and can also be combined with service layers to build scalable and maintainable applications. By mastering @PathVariable, Java beginners can take an important step toward building professional-level backend systems.

Additional Sample Program


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

@RestController
public class GreetingController {

    @GetMapping("/greet/{name}")
    public String greet(@PathVariable String name) {
        return "Hello, " + name + "!";
    }
}

This simple example demonstrates how to extract a name from the URL and return a personalized message. It is a common pattern used in many beginner-level Spring Boot applications.


Hello, Alice!

@GetMapping("/square/{number}")
public int square(@PathVariable int number) {
    return number * number;
}

This example shows how numerical values can be extracted from the URL and used in calculations. Spring automatically converts the value into an integer, making the code concise and easy to understand.


25
Review Conversation Between the Teacher and Student

Student

"I think I understand @PathVariable better now, but when should I use it in real projects?"

Teacher

"You should use @PathVariable when you want to identify a specific resource, such as a user ID or product ID, directly in the URL."

Student

"So it’s mainly for REST API design?"

Teacher

"Exactly. It is widely used in RESTful APIs because it creates clean and meaningful URLs."

Student

"And what about query parameters?"

Teacher

"Query parameters are better for optional values, such as filters or search conditions. @PathVariable is for required path values."

Student

"That makes sense. I can see how this helps organize the structure of an application."

Teacher

"Yes, mastering @PathVariable is an important step in becoming confident with Spring Boot and Java backend development."

Back to Category
Latest Articles
New1
Spring
Spring Boot and Java Version Compatibility Guide: Spring Boot 3.5 3.4 3.3 with Java 21 and Java 17
New
New2
Spring
Complete Guide to Spring Data JPA getReferenceById for Beginners
New
New3
Spring
Complete Guide to Spring Data JPA findAll for Beginners
New
New4
Spring
Spring Data JPA JpaRepository Tutorial for Beginners: Complete Guide to Database Access in Spring Boot
New
Popular Articles
No.1
Java&Spring記事人気No1
Spring
Complete Guide to Spring @GeneratedValue for Java Beginners – Understand Primary Key Generation in JPA
No.2
Java&Spring記事人気No2
Spring
Complete Guide to Spring @PreAuthorize for Java Beginners – Secure Your Application with Method-Level Security
No.3
Java&Spring記事人気No3
Spring
Spring Boot GetMapping Tutorial: Complete Guide to GetMapping in Java for Beginners
No.4
Java&Spring記事人気No4
Spring
Spring @Valid Annotation Tutorial for Beginners: Input Validation in Spring Boot
No.5
Java&Spring記事人気No5
Spring
Mastering the @PostMapping Annotation in Java Spring: A Complete Guide for Beginners
No.6
Java&Spring記事人気No6
Spring
Spring Data JPA Like Query Guide: findByFirstnameLike for Java Beginners
No.7
Java&Spring記事人気No7
Spring
Mastering the @Id Annotation in Java Spring: A Complete Guide for Beginners
No.8
Java&Spring記事人気No8
Spring
Mastering the @Entity Annotation in Java Spring: A Complete Guide for Beginners