spring boot+vue前后端项目的分离(我的第一个前后端分离项目)

本文涉及的产品
RDS Agent(兼容OpenClaw),2核4GB
RDS MySQL DuckDB 分析主实例,基础系列 4核8GB
RDS DuckDB + QuickBI 企业套餐,8核32GB + QuickBI 专业版
简介: 该博客文章介绍了作者构建的第一个前后端分离项目,使用Spring Boot和Vue技术栈,详细说明了前端Vue项目的搭建、后端Spring Boot项目的构建过程,包括依赖配置、数据库连接、服务层、数据访问层以及解决跨域问题的配置,并展示了项目的测试结果。

文章目录

  • 1、前端vue的搭建
  • 2、后端项目的构建
    • pom文件中引入的jar包
    • yml文件用来配置连接数据库和端口的设置
    • application.property进行一些整合
    • controller层(这里返回给前端的数据用json)
    • service层
    • imp层
    • mapper
    • 实体类
    • 额外写一个类、解决跨域问题
  • 3、测试

1、前端vue的搭建

建立项目的过程略
开启一个建立好的vue项目用npm run dev
关闭一个vue项目可在终端操作:ctrl+c
需要注意的几点
1、在建立项目的时候、可以选择路由选项。后续就不需要再次安装路由。
2、安装axiosnpm install --save axios vue-axios

前端项目结构样式
在这里插入图片描述

main.js、这个是整个项目的入口、要使用的在这里引入

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import './plugins/axios'
import App from './App'
import router from './router'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

Vue.js
在这里可以定义跳转到其他页面的连接

<template>
  <div id="app">

    <router-link to="/user">book</router-link>
    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

配置的路由
在这里配置各个页面跳转的路由

import Vue from 'vue'
import Router from 'vue-router'

import UserList from '../components/UserList'
import Home from '../components/Home'


Vue.use(Router)

export default new Router({
  routes: [

  {
    path:'/user',
    component:UserList
    },
    {
      path:'/',
      component:Home
    }
  ]
})

组件1、

<template>
    <div>
      这里是首页
    </div>
</template>

<script>
    export default {
        name: "Home"
    }
</script>

<style scoped>

</style>

组件2
(每个组件之间都可以和后台数据交互通过axios)
提示: const _this =this变量的设置,否则会和回调函数搞混
这里和后台进行连接是通过url。这里的url是访问某一个接口的url,就相当于和某个方法进行打通

<template>
    <div>
      <table class="_table">
        <tr class="_tr">
          <td>姓名</td>
          <td>年龄</td>
          <td>邮箱</td>
        </tr>
        <tr v-for="item in books ">
          <td>{
  
  {item.bookAuthor}}</td>
          <td>{
  
  {item.bookName}}</td>
          <td>{
  
  {item.price}}</td>
        </tr>
      </table>

    </div>
</template>

<script>
    export default {
        name: "UserList",
      data(){
          return{
            books:[
              {
                bookName:'java',
                bookAuthor:'小黑',
                price:'33'
              }
            ]
          }

      },
      created() {
          const _this =this
          axios.get('http://localhost:8181/book/findAll').then(function(resp){
         _this.books=resp.data
          })
      }
    }
</script>

<style scoped>
table,td{
  border: 1px solid silver;
}


</style>

2、后端项目的构建

首先构建项目
目录结构这个样子
在这里插入图片描述

pom文件中引入的jar包

我目前只用到mysql,shiro用来做后续的权限安全验证

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--整合shiro
           subject:用户
           security manager:管理所有的用户
           realm:连接数据库

       -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.4.1</version>
        </dependency>
        <dependency>
            <groupId>com.github.theborakompanioni</groupId>
            <artifactId>thymeleaf-extras-shiro</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!--整合mybatis-->
        <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--   JDBC-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!--  Mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.6</version>
        </dependency>



    </dependencies>

yml文件用来配置连接数据库和端口的设置



spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/ssmbuild?allowMultiQueries=true&characterEncoding=UTF-8&characterSetResults=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    #spring boot 默认是不注入这些属性的,需要自己绑定
    #druid 数据源专有配置
    initiaSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsmMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true

    filters: stat,wall,log4j
    maxPoolPrepareStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500


server:
  port: 8181

application.property进行一些整合


spring.aop.auto=true

#整合mybatis
mybatis.type-aliases-package=com.zheng.pojo
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

controller层(这里返回给前端的数据用json)

这里使用RestController返回的就是return的内容

  • 知识点:@RestController注解相当于@ResponseBody + @Controller合在一起的作用。
    如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。
package com.zheng.controller;


import com.zheng.pojo.Books;
import com.zheng.service.BookService;

import org.springframework.beans.factory.annotation.Autowired;

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("/book")
public class BooksController {

    @Autowired
    BookService bookService;

    //查询所有的书籍信息
    @GetMapping("/findAll")
    public List<Books> findAll() {
        return bookService.queryBookList();
    }


}

service层

package com.zheng.service;

import com.zheng.pojo.Books;

import java.util.List;

public interface BookService {
    /**
     * 查询图书
     */
    public List<Books> queryBookList();


}

imp层

package com.zheng.service.serviceImpl;

import com.zheng.mapper.BooksMapper;
import com.zheng.pojo.Books;
import com.zheng.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    BooksMapper booksMapper;
   //查询书籍
    @Override
    public List<Books> queryBookList() {
        return booksMapper.queryBookList() ;
    }
}

dao层

package com.zheng.mapper;


import com.zheng.pojo.Books;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper    //这个注解表示这个是mybatis的mapeper
@Repository
public interface BooksMapper {


    /**
     * 查询图书
     */
   public List<Books> queryBookList();

}

mapper

、这个位置
在这里插入图片描述

<?xml version="1.0" encoding="UTF8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zheng.mapper.BooksMapper">


    <select id="queryBookList" resultType="com.zheng.pojo.Books">
        select * from bookss

    </select>

</mapper>

实体类

可以使用Lombok、我不喜欢使用

package com.zheng.pojo;

public class Books {
    private String bookId;
    private String bookName;
    private String bookAuthor;
    private Double price;
    private String address;
    private String impression;
    private String introduce;


    public Books(String bookId, String bookName, String bookAuthor, Double price, String address, String impression, String introduce) {
        this.bookId = bookId;
        this.bookName = bookName;
        this.bookAuthor = bookAuthor;
        this.price = price;
        this.address = address;
        this.impression = impression;
        this.introduce = introduce;

    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }


    public Books() { }


    public String getBookId() {
        return bookId;
    }

    public void setBookId(String bookId) {
        this.bookId = bookId;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public String getBookAuthor() {
        return bookAuthor;
    }

    public void setBookAuthor(String bookAuthor) {
        this.bookAuthor = bookAuthor;
    }



    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getImpression() {
        return impression;
    }

    public void setImpression(String impression) {
        this.impression = impression;
    }

    public String getIntroduce() {
        return introduce;
    }

    public void setIntroduce(String introduce) {
        this.introduce = introduce;
    }
}

额外写一个类、解决跨域问题

package com.zheng.config;


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 CrosConfig implements WebMvcConfigurer {
    public void addCorsMappings(CorsRegistry registry){
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}

遇到的问题:
在测试从数据库取数据的时候,那个测试类出了问题。根本原因是spring boot的启动类没有放在根目录。

3、测试

第一步、1、开启后端服务
在这里插入图片描述
第二步、开启前端服务
在这里插入图片描述
看页面效果
在这里插入图片描述
点击book
在这里插入图片描述
这个是从后端请求来的数据。没做样式、简单打通、可以使用elementui让页面更加美观。

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
8月前
|
前端开发 安全 Java
基于springboot+vue开发的会议预约管理系统
一个完整的会议预约管理系统,包含前端用户界面、管理后台和后端API服务。 ### 后端 - **框架**: Spring Boot 2.7.18 - **数据库**: MySQL 5.6+ - **ORM**: MyBatis Plus 3.5.3.1 - **安全**: Spring Security + JWT - **Java版本**: Java 11 ### 前端 - **框架**: Vue 3.3.4 - **UI组件**: Element Plus 2.3.8 - **构建工具**: Vite 4.4.5 - **状态管理**: Pinia 2.1.6 - **HTTP客户端
1112 4
基于springboot+vue开发的会议预约管理系统
|
9月前
|
前端开发 JavaScript Java
基于springboot+vue开发的校园食堂评价系统【源码+sql+可运行】【50809】
本系统基于SpringBoot与Vue3开发,实现校园食堂评价功能。前台支持用户注册登录、食堂浏览、菜品查看及评价发布;后台提供食堂、菜品与评价管理模块,支持权限控制与数据维护。技术栈涵盖SpringBoot、MyBatisPlus、Vue3、ElementUI等,适配响应式布局,提供完整源码与数据库脚本,可直接运行部署。
513 6
基于springboot+vue开发的校园食堂评价系统【源码+sql+可运行】【50809】
|
10月前
|
JSON 分布式计算 大数据
springboot项目集成大数据第三方dolphinscheduler调度器
springboot项目集成大数据第三方dolphinscheduler调度器
674 3
|
10月前
|
Java 关系型数据库 数据库连接
Spring Boot项目集成MyBatis Plus操作PostgreSQL全解析
集成 Spring Boot、PostgreSQL 和 MyBatis Plus 的步骤与 MyBatis 类似,只不过在 MyBatis Plus 中提供了更多的便利功能,如自动生成 SQL、分页查询、Wrapper 查询等。
985 2
|
10月前
|
Java 关系型数据库 MySQL
springboot项目集成dolphinscheduler调度器 实现datax数据同步任务
springboot项目集成dolphinscheduler调度器 实现datax数据同步任务
982 2
|
10月前
|
Java 测试技术 Spring
简单学Spring Boot | 博客项目的测试
本内容介绍了基于Spring Boot的博客项目测试实践,重点在于通过测试驱动开发(TDD)优化服务层代码,提升代码质量和功能可靠性。案例详细展示了如何为PostService类编写测试用例、运行测试并根据反馈优化功能代码,包括两次优化过程。通过TDD流程,确保每项功能经过严格验证,增强代码可维护性与系统稳定性。
369 0
|
10月前
|
存储 Java 数据库连接
简单学Spring Boot | 博客项目的三层架构重构
本案例通过采用三层架构(数据访问层、业务逻辑层、表现层)重构项目,解决了集中式开发导致的代码臃肿问题。各层职责清晰,结合依赖注入实现解耦,提升了系统的可维护性、可测试性和可扩展性,为后续接入真实数据库奠定基础。
767 0
|
分布式计算 大数据 Java
springboot项目集成大数据第三方dolphinscheduler调度器 执行/停止任务
springboot项目集成大数据第三方dolphinscheduler调度器 执行/停止任务
278 0
|
10月前
|
Java 应用服务中间件 Maven
第01课:Spring Boot开发环境搭建和项目启动
第01课:Spring Boot开发环境搭建和项目启动
3095 0
|
前端开发 JavaScript 关系型数据库
前后端分离 -- SpringBoot + Vue实战项目 部署至阿里云服务器
前后端分离 -- SpringBoot + Vue实战项目 部署至阿里云服务器
4368 2
前后端分离 -- SpringBoot + Vue实战项目 部署至阿里云服务器