SpringBoot+Vue豆宝社区前后端分离项目手把手实战系列教程03---实现公告板功能并解决跨域问题

简介: SpringBoot+Vue豆宝社区前后端分离项目手把手实战系列教程03---实现公告板功能并解决跨域问题

豆宝社区项目实战教程简介


本项目实战教程配有免费视频教程,配套代码完全开源。手把手从零开始搭建一个目前应用最广泛的Springboot+Vue前后端分离多用户社区项目。本项目难度适中,为便于大家学习,每一集视频教程对应在Github上的每一次提交。


项目首页截图

image.png


代码开源地址

前端

后端

视频教程地址

视频教程

前端技术栈


Vue

Vuex

Vue Router

Axios

Bulma

Buefy

Element

Vditor

DarkReader


后端技术栈


Spring Boot

Mysql

Mybatis

MyBatis-Plus

Spring Security

JWT

Lombok


后端实现公告


1.实体类

package com.notepad.blog.domain;
import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
// @Builder 支持链式操作 @Accessors 支持链式操作
@Data
@Builder
@Accessors(chain = true)
@TableName("bms_billboard")
public class BmsBillboard implements Serializable {
    private static final long serialVersionUID = 1L;
    /**
     * 主键
     */
    @TableId(type = IdType.AUTO)
    private Integer id;
    /**
     * 公告牌
     */
    @TableField("content")
    private String content;
    /**
     * 公告时间
     */
    @TableField(value = "create_time", fill = FieldFill.INSERT)
    private Date createTime;
    /**
     * 1:展示中,0:过期
     */
    @Builder.Default
    @TableField("`show`")
    private boolean show = false;
}

2.mapper层接口搭建

//@Repository  在启动类 @MapperScan("com.notepad.blog.mapper")
public interface BmsBillboardMapper extends BaseMapper<BmsBillboard> {
}

3.service层搭建

@Service
public class BmsBillboardService extends ServiceImpl<BmsBillboardMapper,BmsBillboard> {
}

4.controller

@RestController
@RequestMapping("/billboard")
public class BmsBillboardController {
    @Autowired
    private BmsBillboardService bmsBillboardService;
    @GetMapping("/show")
    public ApiResult getNotices() {
        BmsBillboard billboard = bmsBillboardService.getNotices();
        return ApiResult.success(billboard);
    }
}

5.service

@Service
public class BmsBillboardService extends ServiceImpl<BmsBillboardMapper, BmsBillboard> {
    @Autowired
    private BmsBillboardMapper billboardMapper;
    public BmsBillboard getNotices() {
        return billboardMapper.getNotices();
    }
}

6.mapper接口

//@Repository  在启动类 @MapperScan("com.notepad.blog.mapper")
public interface BmsBillboardMapper extends BaseMapper<BmsBillboard> {
    BmsBillboard getNotices();
}

7.在mapper/创建BmsBillboardMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.notepad.blog.mapper.BmsBillboardMapper">
    <select id="getNotices" resultType="com.notepad.blog.domain.BmsBillboard">
        SELECT bb.id,
               bb.content,
               bb.create_time,
               bb.SHOW
        FROM bms_billboard bb
        WHERE bb.SHOW = 1
        ORDER BY rand()
        LIMIT 1
    </select>
</mapper>

访问地址测试 :http://localhost:8081/billboard/show


前端实现公告


1.在src下创建/utils/request.js

将下面内容复制即可,简单看看注释

import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
// 1.创建axios实例
const service = axios.create({
  // 公共接口--这里注意后面会讲,url = base url + request url
  baseURL: process.env.VUE_APP_SERVER_URL,
  // baseURL: 'https://api.example.com',
  // 超时时间 单位是ms,这里设置了5s的超时时间
  timeout: 5 * 1000
})
// 设置cross跨域 并设置访问权限 允许跨域携带cookie信息,使用JWT可关闭
service.defaults.withCredentials = false
service.interceptors.response.use(
  // 接收到响应数据并成功后的一些共有的处理,关闭loading等
  response => {
    const res = response.data
    // 如果自定义代码不是200,则将其判断为错误。
    if (res.code !== 200) {
      // 50008: 非法Token; 50012: 异地登录; 50014: Token失效;
      if (res.code === 401 || res.code === 50012 || res.code === 50014) {
        // 重新登录
        MessageBox.confirm('会话失效,您可以留在当前页面,或重新登录', '权限不足', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          window.location.href = '#/login'
        })
      } else { // 其他异常直接提示
        Message({
          showClose: true,
          message: '⚠' + res.message || 'Error',
          type: 'error',
          duration: 3 * 1000
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    /** *** 接收到异常响应的处理开始 *****/
    // console.log('err' + error) // for debug
    Message({
      showClose: true,
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
export default service

2.在根目录下创建 .env


这里请求的是后端地址,注意是建在根目录下,不是src目录里

VUE_APP_SERVER_URL = 'http://localhost:8081'

3.在src下创建/api/billboard.js

请求地址

import request from '@/utils/request'
export function getBillboard() {
    return request({
        url: '/billboard/show',
        method: 'get'
    })
}

4.修改src/home.vue

<template>
  <div>
    <div class="box"> 🔔  {{ billboard.content }} </div>
  </div>
</template>
<script>
import { getBillboard } from "@/api/billboard";
export default {
  name: 'Home',
  data() {
    return {
      billboard: {
        content: "",
      },
    };
  },
  created() {
    this.fetchBillboard();
  },
  methods: {
    async fetchBillboard() {
     getBillboard().then((value) => {
        const { data } = value;
        this.billboard = data;
      });
    },
  },
};
</script>

5.启动项目

yarn serve


image.png

image-20210211185749335


后端跨域


方式一(不推荐):

// controller 上添加
@CrossOrigin

方式二(推荐):

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class GlobalWebMvcConfigurer implements WebMvcConfigurer {
    /**
     * 跨域
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        //允许所有域名进行跨域调用
        config.addAllowedOrigin("*");
        //允许跨越发送cookie
        config.setAllowCredentials(true);
        //放行全部原始头信息
        config.addAllowedHeader("*");
        //允许所有请求方法跨域调用
        config.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}


目录
相关文章
|
4月前
|
监控 Java API
Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程
Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品
779 3
|
2月前
|
监控 Cloud Native Java
Spring Boot 3.x 微服务架构实战指南
🌟蒋星熠Jaxonic,技术宇宙中的星际旅人。深耕Spring Boot 3.x与微服务架构,探索云原生、性能优化与高可用系统设计。以代码为笔,在二进制星河中谱写极客诗篇。关注我,共赴技术星辰大海!(238字)
Spring Boot 3.x 微服务架构实战指南
|
2月前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
427 2
|
3月前
|
消息中间件 Ubuntu Java
SpringBoot整合MQTT实战:基于EMQX实现双向设备通信
本教程指导在Ubuntu上部署EMQX 5.9.0并集成Spring Boot实现MQTT双向通信,涵盖服务器搭建、客户端配置及生产实践,助您快速构建企业级物联网消息系统。
1421 1
|
3月前
|
前端开发 安全 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客户端
413 4
基于springboot+vue开发的会议预约管理系统
|
3月前
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
616 5
|
2月前
|
JavaScript 安全
vue3使用ts传参教程
Vue 3结合TypeScript实现组件传参,提升类型安全与开发效率。涵盖Props、Emits、v-model双向绑定及useAttrs透传属性,建议明确声明类型,保障代码质量。
294 0
|
4月前
|
前端开发 JavaScript Java
基于springboot+vue开发的校园食堂评价系统【源码+sql+可运行】【50809】
本系统基于SpringBoot与Vue3开发,实现校园食堂评价功能。前台支持用户注册登录、食堂浏览、菜品查看及评价发布;后台提供食堂、菜品与评价管理模块,支持权限控制与数据维护。技术栈涵盖SpringBoot、MyBatisPlus、Vue3、ElementUI等,适配响应式布局,提供完整源码与数据库脚本,可直接运行部署。
264 6
基于springboot+vue开发的校园食堂评价系统【源码+sql+可运行】【50809】
|
5月前
|
缓存 前端开发 Java
SpringBoot 实现动态菜单功能完整指南
本文介绍了一个动态菜单系统的实现方案,涵盖数据库设计、SpringBoot后端实现、Vue前端展示及权限控制等内容,适用于中后台系统的权限管理。
489 1