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:

    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:

    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:

    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:

    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:

    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:

    <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

    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

    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接口。

    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前端应用的跨域请求了。

  • 17
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值