Category: Spring Updated: Sep 07, 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?

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

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

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."

Questions from Readers

Questions from Readers
Questions from Readers

Common Questions from Programming Beginners

What is @PathVariable in Spring Boot?

@PathVariable is a Spring MVC annotation used to extract a value directly from a URL path. It is commonly used in Spring Boot REST APIs when a resource is identified by values such as a user ID, product ID, category, or other path information.
Back to Category
Latest Articles
New1
Java
Complete Guide to Java ArrayList add Method: Learn Java Programming Basics for Beginners
Updated
New2
Java
Complete Guide to Java String toString Method: Learn Java Programming Basics for Beginners
Updated
New3
JSP
JSP Comments Explained: How to Write JSP Comments and the Difference from HTML Comments
New
New4
Java
Complete Guide to Java String charAt Method: Learn Java Programming Basics for Beginners
Updated
Popular Articles
No.1
Java&Spring記事人気No1
Thymeleaf
Thymeleaf th:text Complete Guide for Beginners: Displaying Dynamic Text in Spring Boot
No.2
Java&Spring記事人気No2
Spring
Spring Boot and Java Version Compatibility Guide: Spring Boot 3.5 3.4 3.3 with Java 21 and Java 17
No.3
Java&Spring記事人気No3
Thymeleaf
Thymeleaf th:if Complete Guide for Beginners: Conditional Rendering in Spring Boot
No.4
Java&Spring記事人気No4
Thymeleaf
How to Use Thymeleaf th:value: A Beginner-Friendly Guide for Spring Boot Forms
No.5
Java&Spring記事人気No5
Spring
Spring Boot with VS Code Setup Guide for Beginners: Extensions, launch.json, and Hot Reload
No.6
Java&Spring記事人気No6
JSP
JSP Basic Syntax Explained: Scriptlets, Directives, and Expressions for Beginners
No.7
Java&Spring記事人気No7
Spring
Spring Boot @Transactional Annotation Explained: A Beginner's Guide to Database Transactions in Java
No.8
Java&Spring記事人気No8
Spring
Spring Boot ResponseEntity Guide: Headers, Status Codes, and Body Design for Java Beginners