Table of contents
1.
Introduction
2.
Steps to Enhance the Hello World Service
3.
Creating User Bean and User Service
4.
Implementing Get Methods for User Resource
5.
Frequently Asked Questions
5.1.
Why we use PathVariable in Spring Boot?
5.2.
How to make path variable mandatory in Spring Boot?
5.3.
What is the default value of @PathVariable in Spring?
6.
Conclusion
Last Updated: Nov 16, 2024
Medium

Enhancing the Hello World Service with a Path Variable

Author soham Medewar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this blog, we will explore how to enhance a simple "Hello World" service by incorporating a path variable. Path variables allow dynamic data to be passed in the URL, enabling us to personalize the output based on user input. This enhancement takes the basic "Hello World" example beyond a static message, turning it into a more interactive and flexible web service. We will walk through the process of implementing path variables in a web framework like Spring Boot, demonstrating their practical use in real-world applications.

Spring Boot

Steps to Enhance the Hello World Service

To extract the value from the URI, we use the @PathVariable annotation. The @PathVariable annotation is the most suitable for the RESTful web service where the URL contains some value. The use of multiple @PathVariable annotations in the same method is allowed in Spring MVC. A path variable is a crucial path in building rest resources. 

We will create a hello-bean request with a path parameter.

Step 1: Add helloWorldBean() service in the HelloWorldController.java.

HelloWorldController.java

package com.codingninjas.server.main;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.web.bind.annotation.RestController;  
import org.springframework.web.bind.annotation.PathVariable;  

@Configuration  
/* Controller */
@RestController  
public class HelloWorldController   
{  
	/* using get method and hello-world URI  */
	@GetMapping(path="/hello-world")  
	public String helloWorld()  
	{  
		return "Hello World";
	}
	  
	@GetMapping(path="/hello-world-bean")  
	/* method- that returns "Hello World" */
	public HelloWorldBean helloWorldBean()  
	{  
		return new HelloWorldBean("Hello World");/* constructor of HelloWorldBean  */
	} 
	 
	/* passing path variable  */
	@GetMapping(path="/hello-world/path-variable/{variable}")  
	public HelloWorldBean helloWorldPathVariable(@PathVariable String variable)  
	{  
		return new HelloWorldBean(String.format("Hello World, %s", variable)); /* %s replace the variable */
	}  
}  


The controller takes whatever value we give the path variable and returns it to the response.
 

Step 2: Type URL http://localhost:8080///hello-world/path-variable/codingninjas
 

Step 3: Run the HelloWorldContorller.java file. We will see the following response in the browser.

step3

Nextly we will change the path variable. http://localhost:8080///hello-world/path-variable/soham, you will get the following output in the browser.

step 3

Creating User Bean and User Service

We will develop actual resources, users, and the post in this part. To represent the data, a static array list will be used.

Step 1: Build a new package having the name com.codingninjas.server.main.user.
 

Step 2: To store the user detail, create a bean class (User).
 

Step 3: Declare three private variables to store id name and date of birth as id, name, and dob.
 

Step 4: Generate getters and setters.

Go to file -> Source -> Generate Getters and Setters... ->Select All -> Generate.
 

Step 5: Generate toString.

Go to file -> Source -> Generate toString... ->Select All -> Generate.
 

Step 6: Generate constructors.

Go to file -> Source -> Generate Constructor using Fields... -> Generate.

User.java

package com.codingninjas.server.main.user;  

import java.util.Date;  

public class User   
{  
	/* Declaring private variables */
	private String name;  
	private Integer id;  
	private Date dob;  


	public User(Integer id, String name, Date dob)   
	{  
		super();  
		this.name = name; 
		this.id = id;   
		this.dob = dob;  
	}  

	/* gettters */
	public Integer getId()   
	{  
		return id;  
	}  
	public String getName()   
	{  
		return name;  
	} 
	public Date getDob()   
	{  
		return dob;  
	}  


	/* setters */ 
	public void setId(Integer id)   
	{  
		this.id = id;  
	}  
	public void setName(String name)   
	{  
		this.name = name;  
	} 
	public void setDob(Date dob)   
	{  
		this.dob = dob;  
	}  
	
	@Override  
	public String toString()   
	{  
		return String.format("User [id=%s, name=%s, dob=%s]", id, name, dob);  
	}  
} 


Before going on to the next step, move HelloWorldController.java and HelloWorldBean.java in the com.codingninjas.server.main.helloworld package.
 

Step 7: Create UserDaoService class in the com.codingninjas.server.main.user package.

UserDaoService.java

package com.codingninjas.server.main.user;  
import org.springframework.stereotype.Component;  
import java.util.ArrayList;  
import java.util.List;  
import java.util.Date;  

@Component  
public class UserDaoService   
{  
	public static int usersCount=3;  

	/* creating an instance of ArrayList */
	private static List<User> users=new ArrayList<>();  

	/* static block */
	static  
	{  
		// appending users to the list  
		users.add(new User(1, "Soham", new Date()));  
		users.add(new User(2, "Rajat", new Date()));  
		users.add(new User(3, "Mayank", new Date()));  
	}  

	/* retrieving all users from the list */
	public List<User> findAll()  
	{  
		return users;  
	}  

	/* method which adds user in the list  */
	public User save(User user)  
	{  
		if(user.getId()==null)  
		{  
			/* increment user id */
			user.setId(++usersCount);  
		}  
		/* adding user */
		users.add(user);  
		return user;  
	}  


	/* method for finding particular user */
	public User findOne(int ID)  
	{  
		for(User u:users)  
		{  
			if(u.getId()==ID)  
			return u;  
		}  
		return null;  
	}
}  

Implementing Get Methods for User Resource

Step 8: Creating a user controller class “UserResource”.

UserResource.java

package com.codingninjas.server.main.user;  

import java.util.List;  
import org.springframework.web.bind.annotation.RestController;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.beans.factory.annotation.Autowired;  

@RestController  
public class UserResource   
{  
	@Autowired  
	private UserDaoService service;  
	@GetMapping("/users")  
	public List<User> retriveAllUsers()  
	{  
		return service.findAll();  
	}  
}  


Step 9: Run the application. Now type “localhost:8080/users” in the search bar of the browser. This will return the list of users in JSON format.
 

Step 10: We can also display a specific user in the browser using the id of the user. Simply add the mapping “/user/{id}/” and create retrieveUser() method in the UserResource.java.

UserResource.java

package com.codingninjas.server.main.user;  

import java.util.List;  
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.beans.factory.annotation.Autowired;    


@RestController  
public class UserResource   
{  
	@Autowired  
	private UserDaoService service;  
	@GetMapping("/users")  
	public List<User> retriveAllUsers()  
	{  
		return service.findAll();  
	}  


	/* returns the information of specific user */
	@GetMapping("/users/{id}")  
	public User retriveUser(@PathVariable int id)  
	{  
		return service.findOne(id);  
	}  
}  


Step 11: Once again, run the application. Now type “localhost:8080/users/{id}” in the search bar of the browser. You will be getting detailed information about the user associated with that specific id.

Check out this problem - Root To Leaf Path

Frequently Asked Questions

Why we use PathVariable in Spring Boot?

@PathVariable in Spring Boot is used to capture dynamic values from the URL path, allowing flexible and customizable request handling in RESTful APIs.

How to make path variable mandatory in Spring Boot?

To make a path variable mandatory, simply define it in the URL pattern; Spring Boot requires it for the method to work correctly without defaults.

What is the default value of @PathVariable in Spring?

By default, @PathVariable does not have a value unless provided in the URL. If not present, Spring Boot throws an exception or error.

Conclusion

In this article, we have extensively discussed the enhancement of the Hello World Service with a Path Variable. Incorporating a path variable into the "Hello World" service significantly enhances its flexibility and usability. By allowing dynamic inputs through the URL, we can create more interactive and personalized web services. This simple enhancement, while fundamental, opens the door to building more complex and responsive applications in Spring Boot. Understanding how to effectively use path variables is a key skill for developers working with RESTful APIs and building scalable, user-friendly web services.

If you want to learn more, check out our articles on Implementing DELETE Method to Delete a User ResourceTechnological Services in Ready APIWhat Is Web2Py?Why To Use Web2py?Postbacks and Internationalization in web2pyThird Party Modules In Web2pyTasks In Web2py, and  XML in Web2py.

Live masterclass