Spring boot

Spring boot restful web services crud example

Creating a CURD restfull webservices using spring boot

Now creating a restfull web services is much easier using Spring boot.

Configuring pom.xml

To add the necessary dependencies, edit your pom.xml and add the spring-boot-starter-web dependency immediately below the parent section.

For servlet stack applications, the spring-boot-starter-web includes Tomcat by including spring-boot-starter-tomcat.

By adding spring boot web starter to dependency, Spring boot auto-configuration will load all default set of configuration, and you can override them in application.properties if needed.

Spring boot web comes with embedded tomcat, So there will not be any need to add external tomcat to your workspace

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.6.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<groupId>com.candidjava.spring.boot</groupId>
	<artifactId>helloworld</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>helloworld-rest-curd</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

application.yml

Overrides default http port 8080 to 9090

server:
 port: 9090

Creating CURD Rest API using @RestController (StudentController.java)

The first annotation in our StudentConroller class is @RestController. This is known as a stereotype annotation. It provides hints for people reading the code and for Spring that the class plays a specific role. The @RestController annotation tells Spring to render the resulting string directly back to the caller.

@RequestMapping

The @RequestMapping annotation provides “routing” information. It tells Spring that any HTTP request with the /student path should be mapped to this class and act as a prefix for all actions written inside this class.

The @RestController and @RequestMapping annotations are Spring MVC annotations (they are not specific to Spring Boot)

package com.candidjava.springboot.controller;

import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.candidjava.springboot.models.Student;
import com.candidjava.springboot.service.StudentService;

@RestController
@RequestMapping(value = "/student")
public class StudentConroller {
 @Autowired
 StudentService service;

 @PostMapping("/create")
 public void create(@Valid @RequestBody Student student) {
  service.createStudent(student);
 }

 @GetMapping("/getAll")
 public List<Student> get() {
  return service.getAllStudents();
 }

 @GetMapping("/get/{id}")
 public Student getById(@PathVariable("id") String id) {
  return service.getStudentById(id);
 }

 @PutMapping("/update/{id}")
 public void update(@PathVariable("id") String id, @Valid @RequestBody Student student) {
  service.updateStudent(id, student);
 }

 @DeleteMapping("/delete/{id}")
 public void deleteById(@PathVariable("id") String id) {
  this.service.deleteStudentById(id);
 }
}

Simple Service layer (StudentService.java)

Created a dummy service layer to serve student details, In this tutorial i have not integrated and database to it.

package com.candidjava.springboot.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Service;
import com.candidjava.springboot.models.Student;
import com.candidjava.springboot.service.StudentService;

@Service
public class StudentService {

 private List<Student> studentList = new ArrayList<Student>(Arrays.asList(

  new Student("1", "ram", "20"), new Student("2", "arun", "21"), new Student("3", "karthick", "22")

 ));

 public void createStudent(Student student) {
  studentList.add(student);
 }

 public List<Student> getAllStudents() {
  return studentList;

 }

 public Student getStudentById(String id) {
  return studentList.stream().filter(student -> student.getId().equals(id)).findFirst().get();

 }

 public void updateStudent(String id, Student student) {
  int counter = 0;
  for (Student eachStudent: studentList) {
   if (eachStudent.getId().equals(id)) {
    studentList.set(counter, student);
   }
   counter++;
  }
 }

 public void deleteStudentById(String id) {
  studentList.removeIf(student -> student.getId().equals(id));
 }

}

Simple Model class (Student.java)

package com.candidjava.springboot.models;

public class Student {
	private String id;
	private String name;
	private String age;

	public Student(String id, String name, String age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

}

Launch as Spring boot application (SpringApplication.java)

package com.candidjava.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringCrudApplication {

 public static void main(String[] args) {
  SpringApplication.run(SpringCrudApplication.class, args);
 }

}

Download Source

You can download the source code from my github account (Click here)