In this tutorial, we will be covering how to use the PUT and DELETE methods in Spring Web for updating and deleting resources in a RESTful API.
First, let’s start by creating a new Spring Boot project. You can do this by going to https://start.spring.io/ and filling in the necessary project metadata. Make sure to include the "Spring Web" dependency.
Next, create a new package called "controller" in the src/main/java directory of your project. Inside this package, create a new class called "ResourceController".
package com.example.controller;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/resource")
public class ResourceController {
@PutMapping("/{id}")
public String updateResource(@PathVariable Long id, @RequestBody String resource) {
// Logic for updating resource with given id
return "Resource with id " + id + " updated successfully";
}
@DeleteMapping("/{id}")
public String deleteResource(@PathVariable Long id) {
// Logic for deleting resource with given id
return "Resource with id " + id + " deleted successfully";
}
}
In the code above, we have defined two methods for updating and deleting a resource. The @PutMapping
annotation is used for handling HTTP PUT requests, while the @DeleteMapping
annotation is used for handling HTTP DELETE requests. Both methods take a Long id
parameter to identify the resource to update or delete.
Now, let’s create a simple HTML page to test the PUT and DELETE methods. Create a new file called "index.html" in the src/main/resources/static directory of your project.
<!DOCTYPE html>
<html>
<head>
<title>PUT and DELETE Tutorial</title>
</head>
<body>
<h1>Update Resource</h1>
<form id="updateForm" method="PUT">
<label for="id">Resource ID:</label>
<input type="number" id="id" name="id" required>
<label for="resource">New Resource Value:</label>
<input type="text" id="resource" name="resource" required>
<button type="submit">Update Resource</button>
</form>
<h1>Delete Resource</h1>
<form id="deleteForm" method="DELETE">
<label for="id">Resource ID:</label>
<input type="number" id="id" name="id" required>
<button type="submit">Delete Resource</button>
</form>
<script>
const updateForm = document.getElementById('updateForm');
updateForm.addEventListener('submit', async (event) => {
event.preventDefault();
const id = document.getElementById('id').value;
const resource = document.getElementById('resource').value;
const response = await fetch(`/api/resource/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(resource),
});
const data = await response.text();
console.log(data);
});
const deleteForm = document.getElementById('deleteForm');
deleteForm.addEventListener('submit', async (event) => {
event.preventDefault();
const id = document.getElementById('id').value;
const response = await fetch(`/api/resource/${id}`, {
method: 'DELETE',
});
const data = await response.text();
console.log(data);
});
</script>
</body>
</html>
In the HTML code above, we have created a simple form for updating and deleting a resource. When the user submits either form, an asynchronous request is made to the corresponding endpoint defined in the ResourceController class.
Finally, start your Spring Boot application by running the main class. Open your web browser and navigate to http://localhost:8080/index.html to access the HTML page. You can now test the PUT and DELETE methods by entering a resource ID and value to update or delete.
That’s it! You have successfully implemented the PUT and DELETE methods in Spring Web for updating and deleting resources in a RESTful API. Feel free to customize the logic in the ResourceController class to suit your specific requirements.
Index =-1;
Then if we got match the product id with update product id . Then make index as index=i+1
Awesome Video Sir keep uploading videos
Complete the series 💯
I am really happy to have a teacher like u , Thanks for teaching such complicated things easily to us . keep uploading more such videos . Thank you
Navin sir please give the source of get, post, put and delete(upload in the github and share the link in description )
solution used for IndexOutOfBoundException to deleteProduct(productId) is make index=-1;//initialize indicate not found. if(index!=-1){products.remove(index);} else {System.out.println("Product with productId "+productId+" not found.");
You're Amazing Sir. King of Java
So good content, keep it up!
Hii
Could you perhaps explain the PATCH method and give an example in the code?
I think it is very useful and is used regularly in the industry.
BTW standard great videos ! Thanks!
Hi Telusko I would say try to use stream everywhere possible since jdk 8 is a LTS it helps in interviews
if(!(products.removeIf(product -> product.getProdId() == prodId)))
System.out.println("Id not found");
Naveen sir your content is top notch but frequent upload of videos will be great favour for all of us we are excited to learn more and more
takla software engineer
👶👶👶👶👶👶
I am getting this error in spring data jpa project.please anyone help me to sove this error.
Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2024-06-14T18:55:18.718+05:30 ERROR 13152 — [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Illegal UTF8 string in constant pool in class file org/hibernate/boot/registry/classloading/internal/AggregatedClassLoader
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1788) ~[spring-beans-6.1.8.jar:6.1.8]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:600) ~[spring-beans-6.1.8.jar:6.1.8]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522) ~[spring-beans-6.1.8.jar:6.1.8]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:337) ~[spring-beans-6.1.8.jar:6.1.8]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.1.8.jar:6.1.8]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:335) ~[spring-beans-6.1.8.jar:6.1.8]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:205) ~[spring-beans-6.1.8.jar:6.1.8]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:952) ~[spring-context-6.1.8.jar:6.1.8]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:624) ~[spring-context-6.1.8.jar:6.1.8]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) ~[spring-boot-3.3.0.jar:3.3.0]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-3.3.0.jar:3.3.0]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:456) ~[spring-boot-3.3.0.jar:3.3.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:335) ~[spring-boot-3.3.0.jar:3.3.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1363) ~[spring-boot-3.3.0.jar:3.3.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1352) ~[spring-boot-3.3.0.jar:3.3.0]
at com.uniqo.jpademo.JpademoApplication.main(JpademoApplication.java:13) ~[classes/:na]
Caused by: java.lang.ClassFormatError: Illegal UTF8 string in constant pool in class file org/hibernate/boot/registry/classloading/internal/AggregatedClassLoader
at java.base/java.lang.ClassLoader.defineClass1(Native Method) ~[na:na]
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1027) ~[na:na]
at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:150) ~[na:na]
at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:862) ~[na:na]
at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:760) ~[na:na]
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:681) ~[na:na]
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:639) ~[na:na]
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188) ~[na:na]
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:526) ~[na:na]
at org.hibernate.boot.registry.BootstrapServiceRegistryBuilder.build(BootstrapServiceRegistryBuilder.java:184) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.buildBootstrapServiceRegistry(EntityManagerFactoryBuilderImpl.java:515) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:249) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:197) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:63) ~[spring-orm-6.1.8.jar:6.1.8]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:390) ~[spring-orm-6.1.8.jar:6.1.8]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-6.1.8.jar:6.1.8]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-6.1.8.jar:6.1.8]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:366) ~[spring-orm-6.1.8.jar:6.1.8]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1835) ~[spring-beans-6.1.8.jar:6.1.8]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1784) ~[spring-beans-6.1.8.jar:6.1.8]
… 15 common frames omitted
when are we getting next topics video?
great video. Keep it up. Truly dedicated
Keeping doing more and more videos, very very helpful. Thank you
Sir please upload more frequently, this series is simply a gem. Once a video ends we can't wait for the next one. Plz upload more frequently
where is next video ? 🤨 i am waiting
Can`t wait for the next one!!!!!!!