vue+springboot项目开发,使用MySQL示例数据库sakila

vue+spring boot项目开发,使用MySQL示例数据库sakila

从零开始开发一个简单的前后端分离项目,实现对MySQL示例数据库sakila中film表的数据展示。

环境配置

使用IDEA进行后端开发(Spring Boot)
  1. 安装IDEA:参考
  2. JDK的安装及配置:参考
  3. 创建Spring Boot项目:
    • 打开IDEA,选择"Create New Project"
    • 选择"Spring Initializr",填写项目的基本信息
    • 选择JDK11及以上的版本
    • 选择2.6.x及以上版本的Spring Boot
    • 添加项目依赖: Spring Web, Spring Data JPA, MySQL Driver
    • 完成项目创建向导
使用VS Code进行前端开发(Vue.js)
  1. **安装Visual Studio Code (VS Code):**参考
  2. **安装Node.js和npm:**参考
  3. 创建 Vue.js 项目:
    • 打开终端或命令行
    • 全局安装Vue Cli: npm install -g @vue/cli
    • 创建vue.js项目: vue create sakila-frontend
    • 使用模板创建或自定义 (choose defaults or manually select features as needed)

项目开发

Spring Boot 后端开发
  1. 配置MySQL连接:

    路径 src/main/resources/application.properties:

    properties 复制代码
    spring.datasource.url=jdbc:mysql://localhost:3306/sakila?useSSL=false&serverTimezone=UTC
    spring.datasource.username=用户名
    spring.datasource.password=用户密码
    spring.jpa.hibernate.ddl-auto=update
  2. 定义JPA Entity:

    路径src/main/java/com/example/sakila/model/Movie.java:

    java 复制代码
    package com.example.sakila.model;
    
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    @Entity
    @Table(name = "film")
    public class Movie {
        @Id
        private Long filmId;
        private String title;
        private String description;
        // Standard getters and setters
    }
  3. 创建Repository 接口:

    路径src/main/java/com/example/sakila/repository/MovieRepository.java:

    java 复制代码
    package com.example.sakila.repository;
    
    import com.example.sakila.model.Movie;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface MovieRepository extends JpaRepository<Movie, Long> {
    }
  4. 实现Controller:

    路径 src/main/java/com/example/sakila/controller/MovieController.java:

    java 复制代码
    package com.example.sakila.controller;
    
    import com.example.sakila.model.Movie;
    import com.example.sakila.repository.MovieRepository;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import java.util.List;
    
    @RestController
    @RequestMapping("/api/movies")
    public class MovieController {
        private final MovieRepository movieRepository;
    
        public MovieController(MovieRepository movieRepository) {
            this.movieRepository = movieRepository;
        }
    
        @GetMapping
        public List<Movie> getAllMovies() {
            return movieRepository.findAll();
        }
    }
Vue.js前端开发
  1. **安装Axios包:**在项目根目录打开命令行运行 npm install axios.

  2. 创建MovieService

    路径 src/services/MovieService.js:

    javascript 复制代码
    import axios from 'axios';
    
    const API_URL = 'http://localhost:8080/api/movies';
    
    export const getMovies = () => {
        return axios.get(API_URL);
    };
  3. 更新App.vue

    路径 src/App.vue:

    vue 复制代码
    <template>
      <div id="app">
        <div v-for="movie in movies" :key="movie.filmId">
          <h3>{{ movie.title }}</h3>
          <p>{{ movie.description }}</p>
        </div>
      </div>
    </template>
    
    <script>
         import { getMovies } from './services/MovieService';  export default {
         name: 'App',
         data() {
           return {
             movies: [],
           };
         },
         created() {
           getMovies().then(response => {
             this.movies = response.data;
           });
         },
       };
    </script>
运行项目
  • **后端:**使用IDEA运行application,项目会在 http://localhost:8080上运行
  • **前端:**使用终端导航到项目根目录运行npm run serve,项目会在 http://localhost:8081上运行

解决跨域问题

通常涉及在Spring Boot后端添加CORS(跨源资源共享)配置。这允许前端应用(比如运行在不同端口或域名上的Vue.js应用)安全地请求后端资源。下面是具体步骤:

方法1:使用@CrossOrigin注解

在控制器(Controller)或者具体的请求处理方法上使用@CrossOrigin注解来允许跨域请求。这是最快捷的方式,适用于只需要为某几个控制器或方法解决跨域问题的情况。

  • 在控制器上添加@CrossOrigin

    java 复制代码
    import org.springframework.web.bind.annotation.CrossOrigin;
    import org.springframework.web.bind.annotation.RestController;
    
    @CrossOrigin(origins = "http://localhost:8081") // 允许来自8081端口的跨域请求
    @RestController
    public class MovieController {
        // ...
    }
  • 在方法上添加@CrossOrigin

    java 复制代码
    import org.springframework.web.bind.annotation.CrossOrigin;
    import org.springframework.web.bind.annotation.GetMapping;
    
    public class MovieController {
    
        @CrossOrigin(origins = "http://localhost:8081")
        @GetMapping("/movies")
        public List<Movie> getMovies() {
            // ...
        }
    }

方法2:全局CORS配置

如果想为所有控制器和路由统一配置CORS,可以通过实现WebMvcConfigurer接口并覆写addCorsMappings方法来实现。

  1. 创建配置类

    在Spring Boot应用中创建一个新的配置类,比如命名为WebConfig,并使其实现WebMvcConfigurer接口。

    java 复制代码
    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:8081") // 允许来自8081端口的跨域请求
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的请求方法
                    .allowedHeaders("*") // 允许的请求头
                    .allowCredentials(true); // 允许发送Cookie
        }
    }

这个配置类中的addCorsMappings方法会添加针对所有路由(/**)的CORS配置,允许来自指定源(例如http://localhost:8081)的请求,并允许所有方法和头部,还可以配置是否允许凭证(如Cookies)。

注意:

  • 在开发环境中,本案例将前端Vue.js应用运行在localhost:8081上,而Spring Boot后端应用运行在localhost:8080上,这种情况下需要配置CORS来允许跨域请求。
  • 在生产环境中,建议将allowedOrigins设置为前端应用的实际部署域名,而不是使用*,以增强安全性。

通过以上两种方法之一配置CORS后,Spring Boot后端应该能够接受来自Vue.js前端应用的跨域请求了。

相关推荐
升鲜宝供应链及收银系统源代码服务20 分钟前
升鲜宝生鲜配送供应链管理系统---PMS--商品品牌多语言存储与 Redis 缓存同步实现
java·开发语言·数据库·redis·缓存·开源·供应链系统
知兀26 分钟前
【Spring/SpringBoot】<dependencyManagement> + import 导入能继承父maven项目的所有依赖,类似parent
spring boot·spring·maven
全栈前端老曹35 分钟前
【前端组件封装教程】第3节:Vue 3 Composition API 封装基础
前端·javascript·vue.js·vue3·组合式api·组件封装
BruceeLeee37 分钟前
关于vue3中使用el-upload组件上传图片后删除和预览按钮不显示的问题
vue.js
源码宝44 分钟前
企业项目级医院随访系统源码,患者随访管理系统,技术框架:Java+Spring boot,Vue,Ant-Design+MySQL5
java·vue.js·spring·程序·医院管理系统·随访·随访系统源码
郝开1 小时前
Spring Boot 2.7.18(最终 2.x 系列版本):版本概览;兼容性与支持;升级建议;脚手架工程搭建
java·spring boot·后端
苦学编程的谢2 小时前
Redis_8_List
数据库·redis·缓存
香香爱编程2 小时前
electron对于图片/视频无法加载的问题
前端·javascript·vue.js·chrome·vscode·electron·npm
曹天骄2 小时前
阿里云 DCDN → CDN 无缝切换教程(以 example.com 为例)
数据库·阿里云·云计算
清水2 小时前
Spring Boot企业级开发入门
java·spring boot·后端