Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction📜
2.
Implementing Delete Method❎
3.
Frequently Asked Questions
3.1.
What does Spring Boot's post function do?
3.2.
Can we use the POST method to update data in API?
3.3.
What does spring boot's @RestController annotation mean?
3.4.
Can we build a resource using Put rather than POST?
3.5.
Can @component take the place of @controller?
4.
Conclusion
Last Updated: Mar 27, 2024
Easy

Implementing DELETE Method to Delete a User Resource

Author Rajat Agrawal
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction📜

Spring Boot is a project that uses the Spring Framework as its foundation. It makes setting up, configuring, and running simple web-based applications easier and faster. 

Spring Boot is the foundation of every developer's experience, regardless of what they're building. Spring Boot helps us to do it as quickly as possible with the least amount of configuration required upfront. 

REST Spring Boot

In this blog, we will learn how to Implement DELETE Method to Delete a User Resource in spring boot.

Implementing Delete Method❎

Prerequisites: Before implementing the Delete method, you should install Java in your system and set up a project using Spring Tool Suite.

You need to follow some steps to implement a DELETE method to delete a user resource.

Step 1: Open the UserServices.java file.

Step 2: Now, create a method to delete users in the UserServices.java file.

UserServices.java 
 

package com.codingninjas.server.main.user; 
import java.util.Date;  
import java.util.Iterator;   
import java.util.ArrayList;  
import java.util.List;  
import org.springframework.stereotype.Component;  
@Component  
public class UserServices   
{  
public static int usersCount=5;  

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

/*Adding new users to the list*/  
users.add(new User(1, "Rajat", "Delhi"));  
users.add(new User(2, "Rishab", "Mumbai"));  
users.add(new User(3, "Abhinav", "Chennai"));  
users.add(new User(4, "Abhishek", "Kolkata"));  
users.add(new User(5, "Soham", "Bengalore"));  
}  

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

/*Method for adding a user in the list*/   
public User SaveUser(User user)  
{  
if(user.getId()==null)  
{  
user.setId(++usersCount);  
}  
users.add(user);  
return user;  
}  

/*Method to find a particular user from the list*/  
public User FindOneUser(int id)  
{  
for(User user:users)  
{  
if(user.getId()==id)  
return user;  
}  
return null;  
}  

/*Method to delete a user resource*/  
public User DeleteUserById(int id)  
{  
Iterator<User> iterator = users.iterator();  
while(iterator.hasNext())  
{  
User user=iterator.next();  
if(user.getId()==id)  
{  
iterator.remove();  
return user; 
}  
}  
return null;  
}  
}  


Step 3: Now open the UserResources.java file and create a delete mapping to delete a user resource.

UserResources.java 
 

package com.codingninjas.server.main.user;  
import java.net.URI;  
import java.util.List; 
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.PostMapping;  
import org.springframework.web.bind.annotation.RequestBody;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.http.ResponseEntity;  
import org.springframework.web.bind.annotation.RestController; 
import org.springframework.web.bind.annotation.DeleteMapping;  
import org.springframework.web.bind.annotation.GetMapping;   
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;  

@RestController  
public class UserResources   
{  
@Autowired  
private UserServices service;  
@GetMapping("/users")  
public List<User> getAllUsers()  
{  
return service.findAll();  
}  

/*Retrieves a particular user detail*/  
@GetMapping("/users/{id}")  
public User getUser(@PathVariable int id)  
{  
User user= service.findOne(id);  
if(user==null) 
 
/*Throws Runtime exception*/  
throw new UserNotFoundException("id: "+ id);  
return user;  
}  

/*Method to delete a user resource*/  
/*if a user deleted successfully it shows the status 200 OK otherwise returns 404 Not Found*/
@DeleteMapping("/users/{id}")  
public void deleteUser(@PathVariable int id)  
{  
User user= service.deleteById(id);  
if(user==null)  
throw new UserNotFoundException("id: "+ id);  
}  

/*Method to post a new user detail and return the status of the user resource.*/  
@PostMapping("/users")  
public ResponseEntity<Object> createUser(@RequestBody User user)    
{  
User sevedUser=service.save(user);    
URI location=ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(sevedUser.getId()).toUri();  
return ResponseEntity.created(location).build();  
}  
} 


Step 4: Open RestClient in VS Code, give the user_id you want to delete, and select Send Request.

Show All Users:

Show Users

Delete user with id=3:

Delete user

Show the new users list after deleting a user with id=3:

Show new users

Must Read Spring Tool Suite

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Frequently Asked Questions

What does Spring Boot's post function do?

The Spring Boot applications that handle client post requests with JSON data in the header typically utilize the PostMapping() annotation. Launching the project's Spring web.

Can we use the POST method to update data in API?

Yes, we can.

What does spring boot's @RestController annotation mean?

The @Controller and @ResponseBody annotations are already present in the Spring RestController annotation, which is a convenience annotation. Applying this annotation to a class designates it as a request handler. The Spring MVC annotation, Spring RestController, is used to build RESTful web services.

Can we build a resource using Put rather than POST?

You can build or edit a resource using either POST or PUT, as both can be used to submit data. Because PUT is idempotent, it is preferred by many web developers for creating a resource on the server. No matter how often you call PUT, the resource's condition won't be in danger.

Can @component take the place of @controller?

There is no difference between @Component@Service@Controller, and @Repository. The generic annotation @Component is used to represent the component of our MVC.

Conclusion

In this article, we have extensively discussed how to implement DELETE Method to Delete a User Resource in spring boot. I hope you enjoyed reading this article on Implementing DELETE Method to Delete a User Resource.

You can also consider our Spring Boot Course to give your career an edge over others.

Happy Coding!

Previous article
Difference between @Controller and @RestController
Next article
IOC Container in Spring
Live masterclass