您好,登录后才能下订单哦!
随着互联网技术的快速发展,电子商务已经成为现代商业的重要组成部分。为了满足市场需求,开发一个高效、稳定且易于维护的Web商城应用显得尤为重要。本文将详细介绍如何基于Spring Boot和Vue.js搭建一个完整的Web商城应用。
在开始之前,我们需要明确所使用的技术栈:
src
├── main
│ ├── java
│ │ └── com
│ │ └── example
│ │ └── demo
│ │ ├── controller
│ │ ├── service
│ │ ├── repository
│ │ ├── model
│ │ └── DemoApplication.java
│ └── resources
│ ├── application.properties
│ └── static
└── test
└── java
└── com
└── example
└── demo
src
├── assets
├── components
├── router
├── store
├── views
└── main.js
首先,使用Spring Initializr创建一个新的Spring Boot项目。选择以下依赖:
在application.properties
中配置MySQL数据库连接:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
在model
包中创建商品实体类Product
:
package com.example.demo.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
private String description;
// Getters and Setters
}
在repository
包中创建ProductRepository
接口:
package com.example.demo.repository;
import com.example.demo.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository<Product, Long> {
}
在service
包中创建ProductService
类:
package com.example.demo.service;
import com.example.demo.model.Product;
import com.example.demo.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
public List<Product> getAllProducts() {
return productRepository.findAll();
}
public Product getProductById(Long id) {
return productRepository.findById(id).orElse(null);
}
public Product saveProduct(Product product) {
return productRepository.save(product);
}
public void deleteProduct(Long id) {
productRepository.deleteById(id);
}
}
在controller
包中创建ProductController
类:
package com.example.demo.controller;
import com.example.demo.model.Product;
import com.example.demo.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping
public List<Product> getAllProducts() {
return productService.getAllProducts();
}
@GetMapping("/{id}")
public Product getProductById(@PathVariable Long id) {
return productService.getProductById(id);
}
@PostMapping
public Product createProduct(@RequestBody Product product) {
return productService.saveProduct(product);
}
@PutMapping("/{id}")
public Product updateProduct(@PathVariable Long id, @RequestBody Product product) {
product.setId(id);
return productService.saveProduct(product);
}
@DeleteMapping("/{id}")
public void deleteProduct(@PathVariable Long id) {
productService.deleteProduct(id);
}
}
使用Vue CLI创建一个新的Vue项目:
vue create web-mall
选择默认配置或根据需求自定义配置。
安装必要的依赖:
npm install axios vue-router vuex
在router/index.js
中配置路由:
import Vue from 'vue';
import Router from 'vue-router';
import Home from '../views/Home.vue';
import ProductList from '../views/ProductList.vue';
import ProductDetail from '../views/ProductDetail.vue';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/products',
name: 'ProductList',
component: ProductList
},
{
path: '/products/:id',
name: 'ProductDetail',
component: ProductDetail
}
]
});
在store/index.js
中创建Vuex Store:
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
products: []
},
mutations: {
SET_PRODUCTS(state, products) {
state.products = products;
}
},
actions: {
fetchProducts({ commit }) {
axios.get('/api/products')
.then(response => {
commit('SET_PRODUCTS', response.data);
})
.catch(error => {
console.error(error);
});
}
},
getters: {
products: state => state.products
}
});
在views
目录下创建ProductList.vue
和ProductDetail.vue
组件。
<template>
<div>
<h1>Product List</h1>
<ul>
<li v-for="product in products" :key="product.id">
<router-link :to="`/products/${product.id}`">{{ product.name }}</router-link>
</li>
</ul>
</div>
</template>
<script>
import { mapGetters } from 'vuex';
export default {
computed: {
...mapGetters(['products'])
},
created() {
this.$store.dispatch('fetchProducts');
}
};
</script>
<template>
<div>
<h1>{{ product.name }}</h1>
<p>{{ product.description }}</p>
<p>Price: ${{ product.price }}</p>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
product: {}
};
},
created() {
const productId = this.$route.params.id;
axios.get(`/api/products/${productId}`)
.then(response => {
this.product = response.data;
})
.catch(error => {
console.error(error);
});
}
};
</script>
在后端的DemoApplication.java
中添加跨域配置:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:8080")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true);
}
}
分别启动后端和前端项目:
# 后端
mvn spring-boot:run
# 前端
npm run serve
访问http://localhost:8080
,测试商品列表和商品详情功能。
使用以下命令打包前端项目:
npm run build
将打包生成的dist
目录中的文件复制到后端的src/main/resources/static
目录中。
使用以下命令打包后端项目:
mvn clean package
将生成的jar
文件部署到服务器上,并启动应用。
通过本文的步骤,我们成功搭建了一个基于Spring Boot和Vue.js的Web商城应用。这个应用具备了基本的商品管理功能,并且可以通过前后端分离的方式实现高效的开发和部署。希望本文能为你的Web开发之旅提供帮助。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。