Prerequisites
Before we start, ensure you have the following:
- Java Development Kit (JDK) installed
- Apache Maven installed
- Node.js and npm installed
- An IDE (such as IntelliJ IDEA, Eclipse, or VS Code) installed
Spring Boot Vue.js CRUD Full-Stack Application Architecture
Explanation:
-
Vue.js Frontend App:
- Router: Manages routing and navigation within the application.
- Components: Represents the UI elements of the application.
- Services: Handles the business logic and data processing in the frontend.
- Axios HTTP Library: A promise-based HTTP client for making requests to the backend.
-
Spring Boot Backend App:
- Spring REST Controller: Handles incoming HTTP requests and defines endpoints.
- Model: Represents the data structure or entity.
- Service: Contains the business logic.
- DAO (Repository): Interacts with the database.
-
MySQL Database: Stores the application's data.
In this architecture, the Vue.js frontend app communicates with the Spring Boot backend app using Axios to make HTTP requests. The backend app processes these requests, interacts with the MySQL database, and sends responses back to the frontend app.
Step 1: Setting Up the Spring Boot Project
1.1 Create a Spring Boot Project
-
Open Spring Initializr:
- Go to Spring Initializr in your web browser.
-
Configure Project Metadata:
- Project: Maven Project
- Language: Java
- Spring Boot: Select the latest version of Spring Boot 3
- Group: com.example
- Artifact: spring-boot-vue-crud
- Name: spring-boot-vue-crud
- Description: Full Stack Application with Spring Boot and Vue.js
- Package Name: com.example.springbootvuecrud
- Packaging: Jar
- Java Version: 17 (or your preferred version)
- Click
Next
.
-
Select Dependencies:
- On the
Dependencies
screen, select the dependencies you need:- Spring Web
- Spring Data JPA
- H2 Database
- Spring Boot DevTools
- Click
Next
.
- On the
-
Generate the Project:
- Click
Generate
to download the project zip file. - Extract the zip file to your desired location.
- Click
-
Open the Project in Your IDE:
- Open your IDE and import the project as a Maven project.
1.2 Update application.properties
Open the application.properties
file located in the src/main/resources
directory and add the following configuration:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=update
1.3 Create the Product
Entity
In the com.example.springbootvuecrud.model
package, create a new Java class named Product
:
package com.example.springbootvuecrud.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
// Getters and Setters
}
1.4 Create the ProductRepository
Interface
In the com.example.springbootvuecrud.repository
package, create a new Java interface named ProductRepository
:
package com.example.springbootvuecrud.repository;
import com.example.springbootvuecrud.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}
1.5 Create the ProductService
Class
In the com.example.springbootvuecrud.service
package, create a new Java class named ProductService
:
package com.example.springbootvuecrud.service;
import com.example.springbootvuecrud.model.Product;
import com.example.springbootvuecrud.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProductService {
private final ProductRepository productRepository;
@Autowired
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
public List<Product> getAllProducts() {
return productRepository.findAll();
}
public Product saveProduct(Product product) {
return productRepository.save(product);
}
public Product getProductById(Long id) {
return productRepository.findById(id).orElse(null);
}
public void deleteProduct(Long id) {
productRepository.deleteById(id);
}
}
1.6 Create the ProductController
Class
In the com.example.springbootvuecrud.controller
package, create a new Java class named ProductController
:
package com.example.springbootvuecrud.controller;
import com.example.springbootvuecrud.model.Product;
import com.example.springbootvuecrud.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/products")
public class ProductController {
private final ProductService productService;
@Autowired
public ProductController(ProductService productService) {
this.productService = productService;
}
@GetMapping
public List<Product> getAllProducts() {
return productService.getAllProducts();
}
@PostMapping
public Product saveProduct(@RequestBody Product product) {
return productService.saveProduct(product);
}
@GetMapping("/{id}")
public Product getProductById(@PathVariable Long id) {
return productService.getProductById(id);
}
@DeleteMapping("/{id}")
public void deleteProduct(@PathVariable Long id) {
productService.deleteProduct(id);
}
}
Step 2: Creating the Frontend with Vue.js
2.1 Set Up Vue Project
-
Open a terminal and navigate to your workspace directory.
-
Create a new Vue project using Vue CLI:
npm install -g @vue/cli vue create vue-frontend
-
Navigate to the project directory:
cd vue-frontend
2.2 Install Axios
Install Axios to make HTTP requests:
npm install axios
2.3 Create Components
Create the necessary components for displaying and managing products.
2.3.1 Create ProductService.js
Create a new file ProductService.js
in the src
directory to handle API requests for products:
import axios from 'axios';
const API_BASE_URL = "http://localhost:8080/products";
class ProductService {
getAllProducts() {
return axios.get(API_BASE_URL);
}
getProductById(productId) {
return axios.get(`${API_BASE_URL}/${productId}`);
}
createProduct(product) {
return axios.post(API_BASE_URL, product);
}
updateProduct(product) {
return axios.put(`${API_BASE_URL}/${product.id}`, product);
}
deleteProduct(productId) {
return axios.delete(`${API_BASE_URL}/${productId}`);
}
}
export default new ProductService();
2.3.2 Create ProductListComponent.vue
Create a new file ProductListComponent.vue
in the src/components
directory:
<template>
<div>
<h2>Products</h2>
<ul>
<li v-for="product in products" :key="product.id">
{{ product.name }} - ${{ product.price }}
<button @click="editProduct(product)">Edit</button>
<button @click="deleteProduct(product.id)">Delete</button>
</li>
</ul>
<div v-if="editingProduct">
<h3>Edit Product</h3>
<form @submit.prevent="updateProduct">
<input v-model="editingProduct.name" placeholder="Product Name" />
<input v-model="editingProduct.price" placeholder="Product Price" type="number" />
<button type="submit">Update</button>
</form>
</div>
</div>
</template>
<script>
import ProductService from '../ProductService';
export default {
data() {
return {
products: [],
editingProduct: null
};
},
created() {
this.fetchProducts();
},
methods: {
fetchProducts() {
ProductService.getAllProducts().then(response => {
this.products = response.data;
});
},
editProduct(product) {
this.editingProduct = { ...product };
},
updateProduct() {
ProductService.updateProduct(this.editingProduct).then(() => {
this.fetchProducts();
this.editingProduct = null;
});
},
deleteProduct(productId) {
ProductService.deleteProduct(productId).then(() => {
this.fetchProducts();
});
}
}
};
</script>
2.3.3 Create AddProductComponent.vue
Create a new file AddProductComponent.vue
in the src/components
directory:
<template>
<div>
<h2>Add Product</h2>
<form @submit.prevent="addProduct">
<input v-model="product.name" placeholder="Product Name" />
<input v-model="product.price" placeholder="Product Price" type="number" />
<button type="submit">Add</button>
</form>
</div>
</template>
<script>
import ProductService from '../ProductService';
export default {
data() {
return {
product: {
name: '',
price: 0
}
};
},
methods: {
addProduct() {
Product
Service.createProduct(this.product).then(() => {
this.product.name = '';
this.product.price = 0;
});
}
}
};
</script>
2.3.4 Create App.vue
Modify the App.vue
file to include routing for the components:
<template>
<div id="app">
<nav>
<router-link to="/">Products</router-link>
<router-link to="/add-product">Add Product</router-link>
</nav>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App'
};
</script>
<style>
nav {
margin-bottom: 20px;
}
</style>
2.3.5 Update main.js
Ensure the main.js
file is set up correctly:
import { createApp } from 'vue';
import App from './App.vue';
import { createRouter, createWebHistory } from 'vue-router';
import ProductListComponent from './components/ProductListComponent.vue';
import AddProductComponent from './components/AddProductComponent.vue';
const routes = [
{ path: '/', component: ProductListComponent },
{ path: '/add-product', component: AddProductComponent }
];
const router = createRouter({
history: createWebHistory(),
routes
});
const app = createApp(App);
app.use(router);
app.mount('#app');
Step 3: Running the Application
3.1 Run the Spring Boot Application
- Open the
SpringBootVueCrudApplication
class in thesrc/main/java/com/example/springbootvuecrud
directory. - Click the green
Run
button in your IDE or use the terminal to run the application:./mvnw spring-boot:run
3.2 Run the Vue.js Application
-
Open a terminal and navigate to the
vue-frontend
directory. -
Start the Vue application:
npm run serve
-
Open your web browser and navigate to
http://localhost:8080
.
You should now be able to view, add, update, and delete products using the Vue.js frontend and Spring Boot backend.
Conclusion
In this tutorial, we created a full-stack application using Spring Boot for the backend and Vue.js for the frontend. We implemented CRUD operations and handled the necessary configurations to connect the two parts of the application. This setup provides a solid foundation for developing more complex full-stack applications.
Comments
Post a Comment
Leave Comment