如何使用 Spring Boot 和 Ant Design Pro Vue 实现动态路由和菜单功能,快速搭建前后端分离的应用框架

简介: 本文介绍了如何使用 Spring Boot 和 Ant Design Pro Vue 实现动态路由和菜单功能,快速搭建前后端分离的应用框架。首先,确保开发环境已安装必要的工具,然后创建并配置 Spring Boot 项目,包括添加依赖和配置 Spring Security。接着,创建后端 API 和前端项目,配置动态路由和菜单。最后,运行项目并分享实践心得,包括版本兼容性、安全性、性能调优等方面。

随着前后端分离架构的流行,开发一个既高效又易于维护的项目框架变得越来越重要。Spring Boot 作为后端开发的首选框架之一,配合 Ant Design Pro Vue 这样一个现代化的前端 UI 框架,可以快速构建出美观且功能强大的应用。本文将通过一个具体的案例来介绍如何使用 Spring Boot 和 Ant Design Pro Vue 实现动态路由和菜单功能,帮助你快速搭建一个前后端分离的应用框架。

准备工作

首先,确保你的开发环境中已经安装了 Node.js、NPM、Java 开发工具(如 IntelliJ IDEA 或 Eclipse)以及 Spring Boot。

创建 Spring Boot 项目

  1. 初始化 Spring Boot 项目:

    • 使用 Spring Initializr 创建一个新的 Spring Boot 项目,包含 Web 和 Security 依赖。
    • 项目结构如下所示:
      spring-boot-ant-design-pro-vue
      ├── src
      │   ├── main
      │   │   ├── java
      │   │   │   └── com.example.demo
      │   │   │       └── DemoApplication.java
      │   │   └── resources
      │   │       ├── application.properties
      │   │       └── static
      │   └── test
      │       └── java
      └── pom.xml
      
  2. 添加相关依赖:

    • pom.xml 文件中添加 Spring Security 和 Thymeleaf 依赖(用于渲染错误页面):

      <dependencies>
          <!-- Spring Web -->
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-web</artifactId>
          </dependency>
      
          <!-- Spring Security -->
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-security</artifactId>
          </dependency>
      
          <!-- Thymeleaf for error pages -->
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-thymeleaf</artifactId>
          </dependency>
      </dependencies>
      

配置 Spring Security

  1. 创建 Security 配置类:

    • com.example.demo 包下创建 SecurityConfig.java 类:

      package com.example.demo;
      
      import org.springframework.context.annotation.Configuration;
      import org.springframework.security.config.annotation.web.builders.HttpSecurity;
      import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
      
      @Configuration
      public class SecurityConfig extends WebSecurityConfigurerAdapter {
             
      
          @Override
          protected void configure(HttpSecurity http) throws Exception {
             
              http
                  .authorizeRequests()
                      .antMatchers("/api/**").authenticated()
                      .anyRequest().permitAll()
                      .and()
                  .formLogin().disable()
                  .httpBasic();
          }
      }
      

创建后端 API

  1. 创建 Controller:

    • com.example.demo 包下创建 MenuController.java 类:

      package com.example.demo;
      
      import org.springframework.web.bind.annotation.GetMapping;
      import org.springframework.web.bind.annotation.RestController;
      
      import java.util.List;
      import java.util.stream.Collectors;
      import java.util.stream.IntStream;
      
      @RestController
      public class MenuController {
             
      
          @GetMapping("/api/menus")
          public List<MenuDto> getMenus() {
             
              return IntStream.rangeClosed(1, 5)
                  .mapToObj(i -> new MenuDto("Menu " + i, "/menu" + i))
                  .collect(Collectors.toList());
          }
      }
      
      class MenuDto {
             
          private final String title;
          private final String path;
      
          public MenuDto(String title, String path) {
             
              this.title = title;
              this.path = path;
          }
      
          public String getTitle() {
             
              return title;
          }
      
          public String getPath() {
             
              return path;
          }
      }
      

前端部分

  1. 创建 Ant Design Pro Vue 项目:

    • 使用官方脚手架创建项目:
      npm install -g @ant-design/pro-cli
      pro create myapp --type vue
      cd myapp
      npm run start
      
  2. 配置动态路由:

    • src/router/index.js 文件中配置动态路由:

      import Vue from 'vue'
      import Router from 'vue-router'
      import axios from 'axios'
      
      Vue.use(Router)
      
      const routes = []
      
      function loadRoutes() {
             
          axios.get('/api/menus').then(response => {
             
              const menus = response.data
              menus.forEach(menu => {
             
                  routes.push({
             
                      path: menu.path,
                      name: menu.title,
                      component: () => import('@/pages/' + menu.title.replace(' ', '') + '.vue')
                  })
              })
      
              const router = new Router({
             
                  routes: [
                      {
              path: '/', redirect: '/dashboard' },
                      ...routes
                  ]
              })
      
              Vue.prototype.$router = router
          })
      }
      
      loadRoutes()
      
  3. 创建页面组件:

    • 为每个菜单创建一个页面组件,例如 src/pages/Menu1.vue

      <template>
          <a-card>
              <p>这是 Menu 1 页面的内容。</p>
          </a-card>
      </template>
      
      <script>
      export default {
          name: 'Menu1'
      }
      </script>
      
  4. 配置菜单:

    • src/layout/SiderMenu.vue 文件中,使用动态生成的菜单数据:
      // ...
      computed: {
             
          menuData() {
             
              return this.$router.options.routes.map(route => ({
             
                  name: route.name,
                  path: route.path,
                  icon: 'menu-unfold'
              }))
          }
      }
      // ...
      

运行项目

  1. 启动后端服务:

    • 运行 DemoApplication.java 类启动 Spring Boot 服务。
  2. 启动前端服务:

    • 在 Ant Design Pro Vue 项目的根目录下运行 npm run start

实践心得

在实际操作过程中,我们需要注意以下几点:

  • 版本兼容性: 确保使用的 Spring Boot 和 Ant Design Pro Vue 的版本相互兼容。
  • 安全性: 使用 HTTPS 和 JWT 令牌来增强安全性。
  • 性能调优: 根据实际负载情况调整服务器配置。
  • 错误处理: 妥善处理前后端通信中的错误情况。
  • 国际化支持: 为多语言环境添加国际化支持。

通过上述步骤,我们成功地使用 Spring Boot 和 Ant Design Pro Vue 实现了一个具有动态路由和菜单功能的前后端分离框架。这种架构不仅能够提高开发效率,还能使应用更加灵活和可维护。无论是初学者还是经验丰富的开发者,这套方案都值得尝试。

相关文章
|
2月前
|
安全 Java Ruby
我尝试了所有后端框架 — — 这就是为什么只有 Spring Boot 幸存下来
作者回顾后端开发历程,指出多数框架在生产环境中难堪重负。相比之下,Spring Boot凭借内置安全、稳定扩展、完善生态和企业级支持,成为构建高可用系统的首选,真正经受住了时间与规模的考验。
226 2
|
29天前
|
安全 前端开发 Java
《深入理解Spring》:现代Java开发的核心框架
Spring自2003年诞生以来,已成为Java企业级开发的基石,凭借IoC、AOP、声明式编程等核心特性,极大简化了开发复杂度。本系列将深入解析Spring框架核心原理及Spring Boot、Cloud、Security等生态组件,助力开发者构建高效、可扩展的应用体系。(238字)
|
1月前
|
消息中间件 缓存 Java
Spring框架优化:提高Java应用的性能与适应性
以上方法均旨在综合考虑Java Spring 应该程序设计原则, 数据库交互, 编码实践和系统架构布局等多角度因素, 旨在达到高效稳定运转目标同时也易于未来扩展.
110 8
|
2月前
|
监控 Kubernetes Cloud Native
Spring Batch 批处理框架技术详解与实践指南
本文档全面介绍 Spring Batch 批处理框架的核心架构、关键组件和实际应用场景。作为 Spring 生态系统中专门处理大规模数据批处理的框架,Spring Batch 为企业级批处理作业提供了可靠的解决方案。本文将深入探讨其作业流程、组件模型、错误处理机制、性能优化策略以及与现代云原生环境的集成方式,帮助开发者构建高效、稳定的批处理系统。
324 1
|
安全 Java
SpringBoot集成Shiro安全框架
你好: <input type="submit" value="退出"> ADMIN角色 USER角色 SUPERMAN角色 UPDATA权限 DELETE权限 INSERT权限 SELECT权限
868 0
|
安全 Java 数据安全/隐私保护
第16章 SpringBoot集成安全框架
第16章 SpringBoot集成安全框架 16.1 初阶 Security: 默认认证用户名密码 16.2 中阶 Security:内存用户名密码认证 16.
1436 0
|
1月前
|
JavaScript Java 关系型数据库
基于springboot的项目管理系统
本文探讨项目管理系统在现代企业中的应用与实现,分析其研究背景、意义及现状,阐述基于SSM、Java、MySQL和Vue等技术构建系统的关键方法,展现其在提升管理效率、协同水平与风险管控方面的价值。
|
1月前
|
搜索推荐 JavaScript Java
基于springboot的儿童家长教育能力提升学习系统
本系统聚焦儿童家长教育能力提升,针对家庭教育中理念混乱、时间不足、个性化服务缺失等问题,构建科学、系统、个性化的在线学习平台。融合Spring Boot、Vue等先进技术,整合优质教育资源,提供高效便捷的学习路径,助力家长掌握科学育儿方法,促进儿童全面健康发展,推动家庭和谐与社会进步。