Saturday, May 20, 2023

Spring Boot Backend + Vuejs Example [Java tutorial] - Part 1

In this tutorial, we will show you the Vue.js HTTP client and Spring Boot Server example that uses Spring JPA to do the CRUD with the H2 database and Vue.js as frontend technology to make requests and receive responses. But before moving to the Spring Boot and VueJs Example, Let's discuss what is Vuejs and its use cases.

 What is Vuejs?

VueJS is a JavaScript framework that allows you to create dynamic web interfaces. The front end, or vision, receives more attention. It's simple to include into other applications and libraries. VueJS is easy to install, and beginners may quickly learn how to use it and begin creating their own user interfaces.

Advantages of Vue.js

There are certain advantages of using Vue.js, which should encourage developers to use it in their projects. For instance, Vue.js is similar to Angular and React in many aspects, and it continues to enjoy growing popularity compared to other frameworks.

Simplicity - Vue.js is also perfect for working with components because single-file components may store all of the necessary code, including HTML, CSS, and JavaScript, in a single file.

Customization - Vue.js is an excellent development tool because all of its features are easily accessible. Developers can name the function whatever they like for ease of use. Every section can have its own set of functions, making it easy to tailor the application to the user's specific needs.

User-Friendly - Vue.js, according to experts, does not have a steep learning curve, which is advantageous for inexperienced programmers. In terms of learning, it's worth noting that Vue.js just requires programmers to understand the fundamentals of JavaScript, HTML, and CSS, as opposed to Angular or React, which require extra programming languages for advanced development.

Good Documentation - Good documentation is one of the most critical aspects. Vue.js documentation displays all of the framework's choices as well as best practice examples.

And many more advantages you can get. So let's back to our example.

Tools and technologies which is used in this application.

  • You can use any IDE to develop the backend(spring boot) and the frontend of the application.
  • Server: Apache Tomcat
  • Spring Boot 2
  • VueJs
  • H2 Database

So let's create the spring boot backend of the system first. 

The Spring Boot Application

Here, the REST API is used to communicate with the frontend(angular) of the application. Before you start programming, you need to have a better structure of the project. So below is the project structure which is used in this application.

Spring Boot Backend + Vuejs Example [Java tutorial] - Part 1


This application is used to store some data in the in-memory database of H2 and fetch those data. So below are the maven dependencies in the pom.xml file which is used in this example.


<?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.6.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.student</groupId>
<artifactId>crudapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>crudapp</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

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

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

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

</project>


The Application.properties file

SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment: 
        1. config subdirectory of the current directory. 
        2. The current directory 
        3. A classpath /config package 
        4. The classpath root


Below is the used applicaiton.properties file in this Student Crud application.

server.port=8090
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.datasource.url=jdbc:h2:mem:cmpe172
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
 

JPA Entity Class

Below is the used JPA entity class in this application. This is responsible for modeling Students.

package com.student.crudapp.model;

import javax.persistence.*;

@Entity
@Table(name = "STUDENT")
public class Student {

@Column(name = "id")
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

@Column(name = "name")
private String name;

@Column(name = "email")
private String email;

@Column(name = "grade")
private String grade;

public int getId() {
return id;
}

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

public String getName() {
return name;
}

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

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getGrade() {
return grade;
}

public void setGrade(String grade) {
this.grade = grade;
}

@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", grade='" + grade + '\'' +
'}';
}
}

The StudentRepository Interface

As we need to stick with the crud functionality of our system, we need to configure our StudentRepository interface as a Crud repository as below.


package com.student.crudapp.repository;

import com.student.crudapp.model.Student;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface StudentRepository extends JpaRepository<Student, Integer> {

List<Student> findAll();
Student findById(int id);

}

The StudentController Class

Below is the StudentController class which is used in the application. There, we implement the addStudent, findStudent, getAllStudents, updateStudent and deleteStudent methods which are communicating with the H2 database in order to store them in the in-memory database.


package com.student.crudapp.controller;

import com.student.crudapp.model.Student;
import com.student.crudapp.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@CrossOrigin(origins = "http://localhost:8090")
public class StudentController {

@Autowired
StudentRepository studentRepository;

//check the api's working correctly api
@RequestMapping(value="/ping", method=RequestMethod.GET)
@ResponseBody
public String healthCheck() {
return "This is working well";
}


@RequestMapping(value="/students", method=RequestMethod.GET)
@ResponseBody
public List<Student> getAllStudents() {
return studentRepository.findAll();
}

@RequestMapping(value="/student", method=RequestMethod.POST)
@ResponseBody
public Student addStudent(Student student) {
return studentRepository.save(student);
}

@RequestMapping(value="/findstudent", method = RequestMethod.GET)
@ResponseBody
public Student findStudent(@RequestParam("studentId") int studentId) {
return studentRepository.findById(studentId);
}

@RequestMapping(value= "/updatestudent", method = RequestMethod.GET)
@ResponseBody
public Student updateStudent(@RequestBody Student student){
return studentRepository.save(student);
}

@RequestMapping(value="/deletestudent", method = RequestMethod.GET)
@ResponseBody
public int deleteStudent(@RequestParam("studentId") int studentId) {
return studentRepository.deleteById(studentId);
}
}

In the above controller, we used the @CrossOrigin annotation, in order to enable Cross-Origin Resource Sharing (CORS) on the server.
You think this is unnecessary, but the thing is we're deploying our Angular frontend to http://localhost:4200, and our Boot backend to http://localhost:8090, the browser would otherwise deny requests from one to the other. the server.

So below are the created API's in order to deal with frontend of the application.
1. Add a new Student (POST request)
http://localhost:8090/student
{
    "name""Test",
    "email""test@gmail.com",
    "grade""05"
}

2. Get all students (GET request)
http://localhost:8090/students
3. Find specific student(GET request)
http://localhost:8090/findstudent?studentId=1
4. Update student(GET Request)
http://localhost:8090/updatestudent
{
    "id"1,
    "name""Testupdated",
    "email""testupdated@gmail.com",
    "grade""05"
}

5. Delete student(GET request)
http://localhost:8090/deletestudent?studentId=1

Here is the screenshot of the H2 database that we have created.


So now the backend of the application is completed, We need to focus on the frontend of the application which is supposed to build using Vue.js. So let's start working with Vue.js. 


The Vuejs Application

Let's create our first crud application using Vue js. Creating a Vue js app is a comfortable environment for learning Vuejs and it's the best way to start building new applications. Considering this article is already big enough, I am going to create a second part of this article, where I will share Vue.js part, till then keep reading and all the best with your Spring and Spring Boot learning.  Spring 6 and Spring Boot 3 is already here and I also going to write about them soon. Let me know if you want me to cover any specific topic. 



No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.