怎样搭建基于SpringBoot+Vue 的Web商城应用

发布时间:2021-12-02 17:00:53 作者:柒染
来源:亿速云 阅读:203

怎样搭建基于SpringBoot+Vue 的Web商城应用

引言

随着互联网技术的快速发展,电子商务已经成为现代商业的重要组成部分。为了满足市场需求,开发一个高效、稳定且易于维护的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

后端开发

1. 创建Spring Boot项目

首先,使用Spring Initializr创建一个新的Spring Boot项目。选择以下依赖:

2. 配置数据库

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

3. 创建实体类

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
}

4. 创建Repository接口

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> {
}

5. 创建Service层

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);
    }
}

6. 创建Controller层

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);
    }
}

前端开发

1. 创建Vue项目

使用Vue CLI创建一个新的Vue项目:

vue create web-mall

选择默认配置或根据需求自定义配置。

2. 安装依赖

安装必要的依赖:

npm install axios vue-router vuex

3. 配置路由

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
    }
  ]
});

4. 创建Vuex Store

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
  }
});

5. 创建组件

views目录下创建ProductList.vueProductDetail.vue组件。

ProductList.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>

ProductDetail.vue

<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>

前后端联调

1. 配置跨域

在后端的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);
    }
}

2. 启动项目

分别启动后端和前端项目:

# 后端
mvn spring-boot:run

# 前端
npm run serve

3. 测试功能

访问http://localhost:8080,测试商品列表和商品详情功能。

部署

1. 打包前端项目

使用以下命令打包前端项目:

npm run build

2. 部署前端静态文件

将打包生成的dist目录中的文件复制到后端的src/main/resources/static目录中。

3. 打包后端项目

使用以下命令打包后端项目:

mvn clean package

4. 部署后端项目

将生成的jar文件部署到服务器上,并启动应用。

结论

通过本文的步骤,我们成功搭建了一个基于Spring Boot和Vue.js的Web商城应用。这个应用具备了基本的商品管理功能,并且可以通过前后端分离的方式实现高效的开发和部署。希望本文能为你的Web开发之旅提供帮助。

推荐阅读:
  1. 如何搭建母婴社区
  2. 搭建百万 PV 网站架构

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot vue web

上一篇:怎样迁移Spring Boot到函数计算

下一篇:tk.Mybatis插入数据获取Id怎么实现

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》