In this tutorial, we will learn how to build a simple Full Stack application using Vue JS as frontend, Spring boot as backend and we use MySQL database.
Vue JS is a progressive framework for building user interfaces (UI) on the front end.Tools and technologies used
- Spring Boot
- Spring MVC
- Spring Data JPA (Hibernate)
- Eclipse STS
- MySQL Database
- Vue 3
- Axios
- Bootstrap 4
- VS Code
What we will build?
- springboot-backend - Develop and expose REST APIs
- vue-frontend - Consume REST APIs
1. Develop Spring boot application - Backend
1. Create a Spring Boot Application
>> Create Spring Boot Project in Spring Tool Suite [STS]
2. Add maven dependencies
<?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>3.0.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>net.javaguides</groupId>
<artifactId>springboot-backend</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-backend</name>
<description>Spring Boot backend application</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<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>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
3. MySQL Database Configuration
First, you need to create a database in MySQL server with the following command:create database demo
create database demo
Now, let's open the application.properties file in Spring boot project and add MySQL database details to connect to your MySQL database. Here is the application.properties file:spring.datasource.url = jdbc:mysql://localhost:3306/demo?useSSL=false
spring.datasource.username = root
spring.datasource.password = root
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
Make sure that you will change the above database configuration such as JDBC URL, username, and password as per your environment.Hibernate will automatically create database tables so you only need to manually create the database and configure an application.properties file.
spring.datasource.url = jdbc:mysql://localhost:3306/demo?useSSL=false spring.datasource.username = root spring.datasource.password = root ## Hibernate Properties # The SQL dialect makes Hibernate generate better SQL for the chosen database spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect # Hibernate ddl auto (create, create-drop, validate, update) spring.jpa.hibernate.ddl-auto = update
4. Create JPA Entity - Employee.java
package net.javaguides.springboot.entity;
import lombok.*;
import jakarta.persistence.*;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "first_name", nullable = false)
private String firstName;
@Column(name = "last_name")
private String lastName;
private String email;
}
5. Create Spring Data JPA Repository - EmployeeRepository.java
package net.javaguides.springboot.repository;
import net.javaguides.springboot.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
6. Spring Controller with REST API - /api/employees
package net.javaguides.springboot.controller;
import net.javaguides.springboot.entity.Employee;
import net.javaguides.springboot.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api")
@CrossOrigin("http://localhost:3000/")
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;
@GetMapping("/employees")
public List<Employee> fetchEmployees(){
return employeeRepository.findAll();
}
}
@CrossOrigin(origins = "http://localhost:3000")
7. Run Spring Boot Application and Test Rest API
package net.javaguides.springboot;
import net.javaguides.springboot.entity.Employee;
import net.javaguides.springboot.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootBackendApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(SpringbootBackendApplication.class, args);
}
@Autowired
private EmployeeRepository employeeRepository;
@Override
public void run(String... args) throws Exception {
Employee employee1 = Employee.builder()
.firstName("Ramesh")
.lastName("Fadatare")
.email("ramesh@gmail.com")
.build();
Employee employee2 = Employee.builder()
.firstName("Tony")
.lastName("Stark")
.email("tony@gmail.com")
.build();
Employee employee3 = Employee.builder()
.firstName("John")
.lastName("Cena")
.email("cena@gmail.com")
.build();
employeeRepository.save(employee1);
employeeRepository.save(employee2);
employeeRepository.save(employee3);
}
}
Hit this "http://localhost:8080/api/employees" link in a browser will popular list of employees as JSON:
[
{
"id":1,
"firstName":"Ramesh",
"lastName":"Fadatare",
"email":"ramesh@gmail.com"
},
{
"id":2,
"firstName":"Tony",
"lastName":"Stark",
"email":"tony@gmail.com"
},
{
"id":3,
"firstName":"John",
"lastName":"Cena",
"email":"cena@gmail.com"
}
]
Build Vue JS Frontend Application
1. Vue JS Project Setup
To test that you have Node.js and npm correctly installed on your machine, you can type
node --version
npm --version
To install the vue/cli, in a terminal or command prompt type the below command(Note: open cmd using an administrator in Windows. For Mac/Linux, use the sudo before below command to give permission):
npm install -g @vue/cli
This may take a few minutes to install. You can now create a new Vue.js application by typing:
vue create vue-frontend
where vue-frontend is the name of the folder for your application.
Let's quickly run our Vue application by navigating to the new folder and typing npm run serve to start the webserver and open the application in a browser:
cd vue-frontend
npm run serve
2. Install Vetur extension in VS Code
Let's install the Vetur extension in VS code, this extension supplies Vue.js language features (syntax highlighting, IntelliSense, snippets, formatting) to VS Code.npm install bootstrap —save
npm install --save @popperjs/core
import Vue from 'vue'
import App from './App.vue'
import 'bootstrap'
import 'bootstrap/dist/css/bootstrap.min.css'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
4. Vue Service Class - REST API Call
npm add axios
import axios from 'axios';
const EMPLOYEE_API_BASE_URL = 'http://localhost:8080/api/employees';
class EmployeeService{
getEmployees(){
return axios.get(EMPLOYEE_API_BASE_URL);
}
}
export default new EmployeeService();
export default new EmployeeService();
5. Create Vue Component - src/components/Employees.vue
<template>
<div class = "container">
<h1 class = "text-center"> Employees List</h1>
<table class = "table table-striped">
<thead>
<tr>
<th> Employee Id</th>
<th> Employee First Name</th>
<th> Employee Last</th>
<th> Employee Email</th>
</tr>
</thead>
<tbody>
<tr v-for="employee in employees" v-bind:key="employee.id">
<td> {{employee.id }}</td>
<td> {{employee.firstName }}</td>
<td> {{employee.lastName}}</td>
<td> {{employee.email}}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import EmployeeService from '../services/EmployeeService';
export default {
name: 'Employees',
data(){
return {
employees: []
}
},
methods: {
getEmployees(){
EmployeeService.getEmployees().then((response) => {
this.employees = response.data;
});
}
},
created() {
this.getEmployees();
}
}
</script>
One of the first things you would need to understand about Vue is the concept of the component. Vue component is consists of template, script, and style.
- template is nothing but the HTML template with Vue directives
- script is javascript code to write for the Vue module
- style is CSS for the Vue module
created() {
this.getEmployees();
}
methods: { getEmployees() {}} - Any method in a Vue component should be under methods. methods: {
getEmployees(){
EmployeeService.getEmployees().then((response) => {
this.employees = response.data;
});
}
},
EmployeeService.getEmployees().then((response) => {
this.employees = response.data;
});
6. App Component - src/App.vue
Let’s update the App.vue to display the Employees component.<template>
<div id="app">
<Employees />
</div>
</template>
<script>
import Employees from './components/Employees.vue'
export default {
name: 'App',
components: {
Employees
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
7. Run Vue Application
npm run serve
Comments
Post a Comment
Leave Comment