springboot vue前后端数据交互的形式

 axios封装

import axios from 'axios'
import {Message, MessageBox} from 'element-ui'
import store from '../store'
import {getToken} from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 20000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非20000是抛错 可结合自己业务进行修改
     */
    const res = response.data
    // debugger
    if (res.code !== 20000) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

前端请求方式一

import request from '@/utils/request'

export default {
    //讲师列表,分页
    //current当前页,limit每页记录数,teacherQuery分页条件
    getTeacherListPage(current,limit,teacherQuery){
        return request({
            //url: '/table/list/'+current+'/'+limit,
            url: `/eduservice/teacher/pageTeacherCondition/${current}/${limit}`,
            method: 'post',
            //条件的对象,后端使用RequestBody获取属性
            //data表示把对象转换json进行传递到接口
            data: teacherQuery
          }) 
    },
    //删除讲师
    removeDataById(id){
        return request({
            url: `/eduservice/teacher/${id}`,
            method: 'delete'
          }) 
    },
    addTeacher(teacher){
        return request({
            url: `/eduservice/teacher/addTeacher`,
            method: 'post',
            data:teacher
          }) 
    },
    getTeacherInfo(id){
        return request({
            url: `/eduservice/teacher/getTeacherById/${id}`,
            method: 'get'
          })     
    },
    updateTeacher(teacher){
        return request({
            url: `/eduservice/teacher/updateTeacher`,
            method: 'post',
            data:teacher
          })     
    }
}

// export function getList(params) {
//   return request({
//     url: '/table/list',
//     method: 'get',
//     params
//   })
// }

后端接收一

package com.stu.eduservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stu.commonutils.ResultData;
import com.stu.eduservice.entity.EduTeacher;
import com.stu.eduservice.entity.vo.TeacherQuery;
import com.stu.eduservice.service.IEduTeacherService;
import com.stu.servicebase.exceptionHandler.GuliException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 讲师 前端控制器
 * </p>
 *
 * @author stu
 * @since 2021-04-10
 */
@Api(description="讲师管理")
@RestController
@RequestMapping("/eduservice/teacher")
@CrossOrigin  //解决跨域
public class EduTeacherController {

    @Autowired
    private IEduTeacherService eduTeacherService;

    //http://localhost:8001/eduservice/teacher/findAll
    //1查询所有讲师数据 rest风格
    @ApiOperation(value = "所有讲师列表")
    @GetMapping("findAll")
    ResultData findAll(){

        List<EduTeacher> list = eduTeacherService.list(null);
//        try {
//            int a = 10/0;
//        } catch (Exception e) {
//            //执行自定义异常
//            throw new GuliException(200001,"执行自定义异常");
//        }
        list.forEach(i-> System.out.println(i.getName()));
        return ResultData.success().data("list",list);

    }

    //逻辑删除讲师方法
    @ApiOperation(value = "根据ID删除讲师")
    @DeleteMapping("{id}")
    ResultData delete(@ApiParam(name = "id", value = "讲师ID", required = true)
                          @PathVariable String id) {
        boolean flag = eduTeacherService.removeById(id);
        if (flag) {
            return ResultData.success();
        } else {
            return ResultData.error();
        }
    }

    @GetMapping("pageTeacher/{current}/{limit}")
    public ResultData pageTeacher(@PathVariable long current,
                                  @PathVariable long limit){
        Page<EduTeacher> page = new Page<EduTeacher>(current,limit);
        eduTeacherService.page(page,null);

        long total = page.getTotal();
        List<EduTeacher> list = page.getRecords();

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("total",total);
        map.put("list",list);
        //return ResultData.success().data(map);
        return ResultData.success().data("total",total).data("list",list);
    }


    //条件查询,分页
    @PostMapping("pageTeacherCondition/{current}/{limit}")
    public ResultData pageTeacherCondition(@PathVariable long current,
                                           @PathVariable long limit,
                                           @RequestBody(required = false) TeacherQuery teacherQuery ){

        QueryWrapper wrapper = new QueryWrapper();

        String name = teacherQuery.getName();
        Integer level = teacherQuery.getLevel();
        String begin = teacherQuery.getBegin();
        String end = teacherQuery.getEnd();

        if (!StringUtils.isEmpty(name)) {
            wrapper.like("name", name);
        }

        if (!StringUtils.isEmpty(level) ) {
            wrapper.eq("level", level);
        }

        if (!StringUtils.isEmpty(begin)) {
            wrapper.ge("gmt_create", begin);
        }

        if (!StringUtils.isEmpty(end)) {
            wrapper.le("gmt_create", end);
        }
        Page<EduTeacher> page = new Page<EduTeacher>(current,limit);

        eduTeacherService.page(page,wrapper);

        Map<String,Object> map = new HashMap<String,Object>();
        long total = page.getTotal();
        List<EduTeacher> list = page.getRecords();
        map.put("total",total);
        map.put("list",list);
        return ResultData.success().data(map);

    }

    //添加讲师
    @PostMapping("addTeacher")
    public ResultData addTeacher(@RequestBody EduTeacher eduTeacher){

        boolean flag = eduTeacherService.save(eduTeacher);
        if(flag){
            return ResultData.success();
        }else {
            return ResultData.error();
        }
    }

    @ApiOperation(value = "根据ID查询讲师")
    @GetMapping("getTeacherById/{id}")
    public ResultData getTeacherById(
            @ApiParam(name = "id", value = "讲师ID", required = true)
            @PathVariable String id){

        EduTeacher teacher = eduTeacherService.getById(id);
        return ResultData.success().data("teacher", teacher);
    }

//    @ApiOperation(value = "根据ID修改讲师")
//    @PutMapping("{id}")
//    public ResultData updateById(
//            @ApiParam(name = "id", value = "讲师ID", required = true)
//            @PathVariable String id,
//
//            @ApiParam(name = "teacher", value = "讲师对象", required = true)
//            @RequestBody EduTeacher teacher){
//
//        teacher.setId(id);
//        eduTeacherService.updateById(teacher);
//        return ResultData.success();
//    }
    @ApiOperation(value = "修改讲师")
    @PostMapping("updateTeacher")
    public ResultData updateTeacher(@RequestBody EduTeacher teacher){

        boolean flag = eduTeacherService.updateById(teacher);
        if(flag){
            return ResultData.success();
        }else{
            return ResultData.error();
        }

    }

}

前端请求方式二

import request from '@/utils/request'

export default {
    //根据课程id查询小节和小节
    getVideoInfo(videoId){
        return request({

            url: '/eduservice/video/getVideoInfo/'+videoId,
            method: 'get' 
          }) 
    },
    //添加小节
    addVideo(eduVideo){
        return request({

            url: '/eduservice/video/addVideo',
            method: 'post',
            data:eduVideo
            }) 
    },

    //修改小节
    updateVideo(eduVideo){
        return request({

            url: '/eduservice/video/updateVideo',
            method: 'post',
            data:eduVideo
            }) 
    },
    //删除小节
   
    deleteVideo(videoId){
        return request({

            url: '/eduservice/video/'+videoId,
            method: 'delete' 
            }) 
    },
    //删除视频
    removeVideo(id){
        return request({

            url: '/eduvod/video/removeVideo/'+id,
            method: 'delete' 
            }) 
    },
}

后端接收二

package com.stu.eduservice.controller;


import com.stu.commonutils.ResultData;
import com.stu.eduservice.entity.EduVideo;
import com.stu.eduservice.service.IEduVideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author stu
 * @since 2021-05-29
 */
@RestController
@RequestMapping("/eduservice/video")
@CrossOrigin
public class EduVideoController {

    @Autowired
    private IEduVideoService eduVideoService;
    //添加小节
    @PostMapping("addVideo")
    public ResultData addVideo(@RequestBody EduVideo eduVideo){
        eduVideoService.save(eduVideo);
        return ResultData.success();
    }
    //修改小节
    @PostMapping("updateVideo")
    public ResultData updateVideo(@RequestBody EduVideo eduVideo){
        eduVideoService.updateById(eduVideo);
        return ResultData.success();
    }
    //删除小节
    @DeleteMapping("{id}")
    public ResultData deleteVideo(@PathVariable String id){
        eduVideoService.removeById(id);
        return ResultData.success();
    }

    //查询小节
    @GetMapping("getVideoInfo/{videoId}")
    public ResultData getVideoInfo(@PathVariable String videoId){
        EduVideo video = eduVideoService.getById(videoId);
        return ResultData.success().data("video",video);
    }


}

 

posted @ 2021-11-30 00:04  程序员小明1024  阅读(147)  评论(0编辑  收藏  举报