SpringBoot&Vue 前后端分离项目框架搭建

SpringBoot&Vue   前后端分离项目框架搭建


事先确定数据库结构:

这里一切从简,Navicat创建新的数据库以及表结构:

在这里插入图片描述

在这里插入图片描述

1.安装Vue

  • 1.下载底层支持node.js
  • 2.通过npm安装vue-cli(npm install @vue/cli -g)

2.创建Vue项目

  • 1.选择项目文件夹创建项目(vue create [项目文件名])
  • 2.试验是否创建Vue项目成功(按照cmd命令行提示即可)
  • 3.Element-Plus安装(npm install element-plus --save)

在这里插入图片描述

  • 4.axios安装(npm install axios --save)
  • 5.改造前端页面(没学到火候,页面还是丑)

主体:
在这里插入图片描述

点击新增(比如:[2021,张三,20]):

在这里插入图片描述

查询支持学号查询,姓名模糊查询以及年龄查询(比如:王,19):

在这里插入图片描述

在这里插入图片描述
点击张三所在行(编辑按键)修改(比如:[2020,李四,21]):

在这里插入图片描述

在这里插入图片描述
点击李四所在(删除按键),再次确认点击删除:

在这里插入图片描述

在这里插入图片描述

vue.config.js:

跨域问题解决

module.exports = {
  devServer:{
    proxy:{
      '/api':{ // 设置拦截器
        target: 'http://localhost:8888', // 设置代理目标地址
        changeOrigin: true, //是否设置同源
        pathRewrite:{
          '/api':'' // 代理之后将/api替换为空字符串
        }
      }
    }
  }
}

network/request.js:

aioxs请求

import axios from  'axios'

// 这里config作为配置参数,success作为成功回调函数,failure作为失败回调函数
export function request(config){
  const instance = axios.create({
    baseURL: "/api",
    timeout: 3000
  })
  instance.interceptors.request.use(config => {
    // 不作拦截
    return config;
  },err => {
    console.log(err);
  })
  instance.interceptors.response.use(res => {
    return res.data; // 返回data即可
  },err => {
   return err;
  })
  return instance(config);
}

main.js:

import {createApp} from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'


createApp(App).
use(ElementPlus ).
use(store).
use(router).
mount('#app')

App.vue:

<template>
  <!-- 中文语言配置 -->
  <el-config-provider :locale="locale">
    <div id="app">
      <Header></Header>
      <router-view />
    </div>
  </el-config-provider>
</template>

<script>
import Header from './components/Header'
import { ElConfigProvider } from 'element-plus'
import zhCn from 'element-plus/lib/locale/lang/zh-cn'
export default{
  name: 'App',
  components:{
    Header,
    ElConfigProvider
  },
  setup() {
    return {
      locale: zhCn,
    }
  },
}
</script>

<style>
</style>

Home.vue:

<template>
  <div id="home">
    <el-row>
      <el-col :span="3">
          <Sidebar></Sidebar>
      </el-col>
      <el-col :span="21"
              v-loading="loading"
              element-loading-text="加载中..."
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(111,111,111, 0.6)">
          <Table @emitLoadingFlag="acceptLoadingFlag"></Table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import Sidebar from '../components/Sidebar'
  import Table from '../components/Table'

  export default {
    name: 'Home',
    data(){
      return {
        loading: false
      }
    },
    components: {
      Sidebar,
      Table
    },
    methods:{
      acceptLoadingFlag(loading){
        this.loading = loading;
      }
    }
  }
</script>

<style scoped>
</style>

About.vue:

<template>
  <div id="about">
    <h1>这是About页面</h1>
    <el-button>按钮</el-button>
  </div>
</template>

router/index.js:

import { createRouter, createWebHistory } from 'vue-router'
const Home = () => import('@/views/Home')
const About = () => import('@/views/About')

const routes = [
  {
    path: '/',
    name: 'default',
    component: Home
  },
  {
    path: '/home',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: About
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

components/Header.vue:

<template>
  <div id="header">
    <el-menu
            mode="horizontal"
            background-color="#545c64"
            text-color="#fff"
            active-text-color="#ffd04b"
            default-active="1"
    >
      <el-menu-item index="1" @click="homeClick" >首页</el-menu-item>
      <el-menu-item index="2" @click="aboutClick">关于</el-menu-item>
      <el-sub-menu  index="3" >
        <template #title>张三</template>
        <el-menu-item index="3-1">个人信息</el-menu-item>
        <el-menu-item index="3-2">退出系统</el-menu-item>
      </el-sub-menu>
    </el-menu>
  </div>
</template>

<script>
  export default {
    name: "Header",
    methods:{
      homeClick(){
        this.$router.push('/home')
      },
      aboutClick(){
        this.$router.push('/about')
      }
    }
  }
</script>

<style scoped>
</style>

components/Sidebar.vue:

<template>
  <el-menu
          active-text-color="#ffd04b"
          background-color="#545c64"
          class="el-menu-vertical-demo"
          default-active="1"
          text-color="#fff"
  >

    <el-menu-item index="1">
      <i class="el-icon-menu"></i>
      <span>系统管理</span>
    </el-menu-item>

    <el-menu-item index="2">
      <i class="el-icon-menu"></i>
      <span>用户管理</span>
    </el-menu-item>

    <el-menu-item index="3">
      <i class="el-icon-menu"></i>
      <span>设置</span>
    </el-menu-item>
  </el-menu>
</template>

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

<style scoped>
  .el-menu-vertical-demo{
    min-height: 92vh;
  }
</style>

components/Table.vue:

<template>
  <el-col>
    <el-button style="margin-top: 15px;margin-left: 10px" @click="insertClick" type="primary">新增</el-button>
      <el-button style="margin-top: 15px;margin-left: 900px" type="primary" @click="findClick">查询</el-button>
      <el-input
              style="width: 300px"
              v-model="searchValue"
              placeholder="请输入关键字"
              prefix-icon="el-icon-search" clearable/>
  </el-col>
  <el-table
          :data="tableData"
          border stripe size="medium">
    <el-table-column prop="studentId" label="学号" align="center"/>
    <el-table-column prop="studentName" label="姓名" align="center"/>
    <el-table-column prop="studentAge" label="年龄" align="center"/>
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
        <el-popover  placement="top" :width="160" v-model:visible="popOver[scope.$index]" trigger="click" >
          <p>确认删除吗?</p>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" typ="text" @click="popOver[scope.$index] = false"
            >取消</el-button>
            <el-button type="primary" size="mini" @click="deleteStudent(scope.$index)"
            >确认</el-button>
          </div>
          <template #reference>
            <el-button type="danger" size="mini" @click="popOverClick(scope.$index)">删除</el-button>
          </template>
        </el-popover>
      </template>

    </el-table-column>
  </el-table>
  <div align="center" style="padding: 0;position: fixed;bottom: 30px;left: 65ch;">
    <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
                   v-model:current-page="currentPage"
                   v-model:page-size="pageSize"
                   :page-sizes="[10,15]"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange">
    </el-pagination>
  </div>
  <el-dialog
          v-model="dialogVisible"
          title="添加学生信息"
          width="30%">

    <el-form
            ref="ruleForm"
            status-icon
            label-width="120px"
            class="demo-ruleForm"
            v-model="formData">

      <el-form-item label="学生学号">
        <el-input v-model="formData.studentId"></el-input>
      </el-form-item>
      <el-form-item label="学生姓名">
        <el-input v-model="formData.studentName"></el-input>
      </el-form-item>
      <el-form-item label="学生年龄">
        <el-input v-model="formData.studentAge"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitClick">添加</el-button>
        <el-button @click="resetClick">重置</el-button>
        <el-button @click="insertCancelClick">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <el-dialog
          v-model="updateDialogVisible"
          title="修改学生信息"
          width="30%">

    <el-form
            ref="ruleForm"
            status-icon
            label-width="120px"
            class="demo-ruleForm"
            v-model="updateFormData">

      <el-form-item label="学生学号">
        <el-input v-model="updateFormData.studentId"></el-input>
      </el-form-item>
      <el-form-item label="学生姓名">
        <el-input v-model="updateFormData.studentName"></el-input>
      </el-form-item>
      <el-form-item label="学生年龄">
        <el-input v-model="updateFormData.studentAge"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="updateSubmitClick">修改</el-button>
        <el-button @click="updateResetClick">重置</el-button>
        <el-button @click="updateCancelClick">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

</template>

<script>
  import {request} from "@/network/request.js"
  import { ElMessage } from 'element-plus'
  export default {
    name: "Table",
    created(){
      // 初始化操作
      this.init();
    },
    data() {
      return {
        totalData: null,
        tableData: null,
        searchValue: '',
        currentPage: 1, // 默认
        pageSize: 10, // 默认
        total: null,
        dialogVisible: false,
        loading: true,
        formData: {
          // 由于是RequestBody,所以需要保持与Student类属性一致… 
          studentName: null,
          studentId: null,
          studentAge: null
        },
        row: null,
        updateDialogVisible: false,
        updateFormData: {
          studentId: null,
          studentName: null,
          studentAge: null
        },
        popOver:false
      }
    },
    methods: {
      init(){
        request({
          url: '/all_students',
          method: 'get'
        }).then(res => {
          this.totalData = res;
          this.total = res.length;
          this.popOver = new Array(this.pageSize).fill(false); //初始化当前表格中的popOver选项
          this.showPage(); // 异步请求有坑… 不能放到外面…
        })
      },// 页面更新初始化操作
      insertClick(){
        this.dialogVisible = true
      },// 显示页面数据
      showPage(){
        this.tableData = [];
        for(let i = (this.currentPage - 1)*this.pageSize ; i < this.currentPage*this.pageSize ; i++){
          if(this.totalData[i] != null){
            this.tableData.push(this.totalData[i]);
          }
        }
      },// 显示页面数据
      submitClick(){
        if(this.formData.studentId == null || this.formData.studentName == null){
          // 提交失败判断… 
          ElMessage({
              showClose: true,
              message: '添加失败',
              type: 'error',
            });
          return;
        }
        request({
          url: "/add_student",
          method: 'post',
          data: this.formData
        }).then(res => {
          if(res == 2001){ // 失败处理
            ElMessage({
              showClose: true,
              message: '添加失败',
              type: 'error',
            });
          }else if(res == 2000){
            ElMessage({
              showClose: true,
              message: '添加成功',
              type: 'success'
            });
            this.resetClick();
            this.dialogVisible = false; // 还原
          }
          this.init();
        })
      }, // 提交新增学生信息
      handleCurrentChange(val){
        this.currentPage = val;
        this.showPage();
      },
      handleSizeChange(val){
        this.pageSize = val;
        this.popOver = new Array(this.pageSize).fill(false); //初始化当前表格中的popOver选项
        console.log(this.popOver);
        this.showPage();
      },
      insertCancelClick(){
        this.resetClick()
        this.dialogVisible = false
      },
      deleteStudent(index) {
        this.popOver[index] = false;
        //console.log("请求数据为;",this.totalData[index + (this.currentPage - 1) * this.pageSize]);
        request({
          url: '/delete_student',
          method: 'get',
          params:{
            id: this.totalData[index+(this.currentPage-1)*this.pageSize].studentId
          }
        }).then(res => {
          if(res == 2000){ // 请求成功
            ElMessage({
              showClose: true,
              message: '删除成功',
              type: 'success'
            });
            this.init();
          }else if(res == 2001){ // 请求失败
            ElMessage({
              showClose: true,
              message: '删除失败',
              type: 'error',
            });
          }
        })
        this.init();
      },
      resetClick(){
        this.formData.studentName = null;
        this.formData.studentId = null;
        this.formData.studentAge = null;
      },
      findClick(){
        this.$emit('emitLoadingFlag',true); // 打开加载图标…
        if(this.searchValue == ''){
          // 直接初始化
          this.init();
          this.$emit('emitLoadingFlag',false);
          return;
        }

        this.totalData = null;
        this.total = 0;
        this.currentPage = 1;
        this.tableData = null;
        request({
          url: '/student_id',
          method: 'get',
          params:{
            id: this.searchValue
          }
        }).then(res => {
          if(res != null){// 查找成功
            this.totalData = res;
            this.total = 0;
            for(let item of this.totalData){
              this.total ++;
            }
            this.currentPage = 1;
            this.showPage();
            this.$emit('emitLoadingFlag',false);
            return ;
          }
          request({
            url: '/student_name',
            method: 'get',
            params: {
              name: this.searchValue
            }
          }).then(res => {
            if(res.length != 0){ // 查找成功
              this.totalData = res;
              this.total = 0;
              for(let item of this.totalData){
                this.total ++;
              }
              this.currentPage = 1;
              this.showPage();
              this.$emit('emitLoadingFlag',false);
              return ;
            }

            request({
              url: '/student_age',
              method: 'get',
              params:{
                age: this.searchValue
              }
            }).then(res => { // 查找成功
              if(res.length != 0){
                this.totalData = res;
                this.total = 0;
                for(let item of this.totalData){
                  this.total ++;
                }
                this.currentPage = 1;
                this.showPage();
                this.$emit('emitLoadingFlag',false);
                return ;
              }
            })
          })
        }).catch(err => {
          console.log(err);
        })
      },
      handleEdit(row){
        this.row = row;
        this.updateDialogVisible = true;
      },
      updateSubmitClick(){

        request({
          url: '/update_student',
          method: 'post',
          data:{
            studentId: this.updateFormData.studentId,
            studentName: this.updateFormData.studentName,
            studentAge: this.updateFormData.studentAge,
          },
          params:{
            id:this.row.studentId
          }
        }).then(res => {
          if(res == 2000){ // 请求成功
            ElMessage({
              showClose: true,
              message: '修改成功',
              type: 'success'
            });
            this.updateResetClick();
            this.updateDialogVisible = false; // 还原
          }else if(res == 2001){ // 请求失败
            ElMessage({
              showClose: true,
              message: '修改失败',
              type: 'error',
            });
          }
        })
        this.init();
      },
      updateResetClick(){
        this.updateFormData.studentId = null;
        this.updateFormData.studentName = null;
        this.updateFormData.studentAge = null;
      },
      updateCancelClick(){
        this.updateResetClick();
        this.updateDialogVisible = false;
      },
      popOverClick(index){
        this.popOver[index] = true; // 将当前的popover设置为可见… 
      }
    }
  }
</script>

<style scoped>
</style>

3.创建Springboot项目

  • 1.创建Springboot项目

项目基本结构(vue导入,配置数据库等):

在这里插入图片描述

在这里插入图片描述

相关依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.wu</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.11.3</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>org.wu.demo.DemoApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

application.properties:

# 应用名称
spring.application.name=demo
# 应用服务 WEB 访问端口
server.port=8888
#下面这些内容是为了让MyBatis映射
#指定Mybatis的Mapper文件
mybatis.mapper-locations=classpath:mappers/*xml
#指定Mybatis的实体目录
mybatis.type-aliases-package=org.wu.demo.entity
# 数据库驱动:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据源名称
spring.datasource.name=defaultDataSource
# 数据库连接地址
spring.datasource.url=jdbc:mysql://localhost:3306/spring-vue?serverTimezone=UTC
# 数据库用户名&密码:
spring.datasource.username=root
spring.datasource.password=root

Application.java:

package org.wu.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("org.wu.demo.mapper")
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Student.java:

package org.wu.demo.entity;

import lombok.Data;

@Data
public class Student {
    private Integer studentId;
    private String studentName;
    private Integer studentAge;
}

StudentMapper.java:

package org.wu.demo.mapper;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import org.wu.demo.entity.Student;

import java.util.List;

@Repository("studentMapperBean")
public interface StudentMapper {
    Student queryStudentById(String id);
    List<Student> queryStudentsByName(String name);
    List<Student> queryStudentsByAge(String age);
    List<Student> queryStudentsByPage(@Param("pageSize") int pageSize,@Param("start") int start);
    List<Student> findAllStudents();
    int countStudents();
    void addStudent(Student student);
    void deleteStudentById(int id);
    void updateStudent(@Param("id")int id , @Param("student")Student student);
}

StudentService.java:

package org.wu.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.wu.demo.entity.Student;
import org.wu.demo.mapper.StudentMapper;

import java.util.List;

@Service("studentServiceBean")
public class StudentService {
    private StudentMapper studentMapper;

    @Autowired
    @Qualifier("studentMapperBean")
    private void setStudentMapper(StudentMapper studentMapper){
        this.studentMapper = studentMapper;
    }
    public Student queryStudentById(String id){
        return studentMapper.queryStudentById(id);
    }
    public List<Student> queryStudentsByName(String name){
        return studentMapper.queryStudentsByName(name);
    }
    public List<Student> queryStudentsByAge(String age){
        return studentMapper.queryStudentsByAge(age);
    }
    public List<Student> queryStudentsByPage(int pageSize,int currPage){
        return studentMapper.queryStudentsByPage(pageSize,(currPage - 1)*pageSize);
    }
    public List<Student> findAllStudents(){
        return studentMapper.findAllStudents();
    }
    public int countStudents(){
        return studentMapper.countStudents();
    }
    public void addStudent(Student student){
        studentMapper.addStudent(student);
    }
    public void deleteStudentById(int id){
        studentMapper.deleteStudentById(id);
    }
    public void updateStudent(int id,Student student){
        studentMapper.updateStudent(id,student);
    }
}

StudentController.java:

package org.wu.demo.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jdk.nashorn.internal.ir.ObjectNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.wu.demo.entity.Student;
import org.wu.demo.service.StudentService;

import java.util.ArrayList;
import java.util.List;

@RestController
public class StudentController {

    private StudentService studentService;

    @Autowired
    @Qualifier("studentServiceBean")
    public void setStudentService(StudentService studentService){
        this.studentService = studentService;
    }
    @GetMapping(value="/student_id")
    public String queryStudentById(String id){
        Student student = studentService.queryStudentById(id);
        ObjectMapper mapper = new ObjectMapper();
        String result = null;
        try {
            result = mapper.writeValueAsString(student);
            return result;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }
    @GetMapping(value="/student_name")
    public String queryStudentByName(String name){
        List<Student> studentList = studentService.queryStudentsByName(name);
        ObjectMapper mapper = new ObjectMapper();
        String result = null;
        try {
            result = mapper.writeValueAsString(studentList);
            return result;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }
    @GetMapping(value="/student_age")
    public String queryStudentByAge(String age){
        List<Student> studentList = studentService.queryStudentsByAge(age);
        ObjectMapper mapper = new ObjectMapper();
        String result = null;
        try {
            result = mapper.writeValueAsString(studentList);
            return result;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }
    @GetMapping(value="/page")
    public String queryStudentByPage(Integer pageSize,Integer currPage){
        List<Student> studentList = studentService.queryStudentsByPage(pageSize,currPage);
        ObjectMapper mapper = new ObjectMapper();
        String result = null;
        try {
            result = mapper.writeValueAsString(studentList);
            return result;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }
    @GetMapping(value="/all_students")
    public String findAllStudents()
    {
        ArrayList<Student> studentList = (ArrayList<Student>) studentService.findAllStudents();
        ObjectMapper mapper = new ObjectMapper();
        String result = null;
        try {
            result = mapper.writeValueAsString(studentList);
            return result;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }
    @GetMapping(value="/count_students")
    public int countStudents(){

        return studentService.countStudents();
    }
    // 这里json参数返回的key应该为Student对象的键
    @PostMapping(value="/add_student")
    public int addStudent(@RequestBody Student student){
        try{
            studentService.addStudent(student);
            return 2000; // 成功码
        }catch(Exception e){
            return 2001; // 失败码
        }
    }
    @GetMapping(value="/delete_student")
    public int deleteStudent(Integer id){
        try{
            studentService.deleteStudentById(id);
            return 2000;
        }catch(Exception e){
            return 2001;
        }
    }
    @PostMapping(value="/update_student")// @RequestParam可以有多个,@RequestBody最多只有一个
    public int updateStudent(@RequestParam("id") Integer id, @RequestBody Student student){
        try{
            studentService.updateStudent(id,student);
            return 2000;
        }catch(Exception e){
            e.printStackTrace();
            return 2001;
        }
    }
}

StudentMapping.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 = "org.wu.demo.mapper.StudentMapper">

    <resultMap id = "studentResultMap" type = "org.wu.demo.entity.Student">
        <id property = "studentId" column="id" />
        <result property = "studentName" column="name" />
        <result property = "studentAge" column = "age" />
    </resultMap>

    <select id="queryStudentById" parameterType="String" resultMap="studentResultMap">
        select * from student where id=#{id}
    </select>
    <select id="queryStudentsByName" parameterType="String" resultMap="studentResultMap">
        select * from student where `name` like CONCAT('%',#{name},'%')
    </select>
    <select id="queryStudentsByAge" parameterType="String" resultMap="studentResultMap">
        select * from student where age = #{studentAge}
    </select>
    <select id="queryStudentsByPage" resultMap="studentResultMap">
        select * from student limit #{start},#{pageSize}
    </select>
    <select id="findAllStudents" resultMap="studentResultMap">
        select * from student
    </select>
    <select id="countStudents" resultType="int">
        select count(*) from student
    </select>
    <insert id="addStudent" parameterType="Student">
        insert into student(id,`name`,age)
        values(#{studentId},#{studentName},#{studentAge})
    </insert>
    <delete id="deleteStudentById" parameterType="int">
        delete from student where id=#{id}
    </delete>
    <update id="updateStudent" >
        update student set `name` = #{student.studentName},
        age = #{student.studentAge},
        id = #{student.studentId}
        where id = #{id}
    </update>
</mapper>


保证API都能请求成功到(如下):

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值