vue+elementui+springboot实现前后端分离的小例子(后端部分)

408 阅读3分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

前后端分离有什么好处?

1、前端js可以做很多数据处理的工作,减小服务器的压力。 2、后台的错误不会直接反映到前台。 3、前后端工程师约定交互接口,实现并行开发,可以提高开发效率,同时代码可以更好的维护。

前后端分离会存在跨域的问题,什么是跨域呢?

当一个请求url的协议、域名、端口三者之间任意一个与当前页面url不同即为跨域。

打个比方,后端运行的项目占用了8080端口,前端运行的项目就不能使用8080端口了,可以使用8081端口,那么前端调用后端接口时就存在跨域的问题。

关键代码如下: (后端对应的controller上记得加上@CrossOrigin注解处理跨域)

//指定请求方法,然后放上后端的接口,如果成功,显示成功的弹窗,再执行回调函数进行页面的刷新
axios.post('http://localhost:8080/find').then(function(resp){
                    _this.$alert('find!!!' , 'message',{
                        confirmButtonText: 'yes',
                        //回调函数,操作完成后刷新该页面
                        callback: action => {
                           window.location.reload()
                        }
                    })
            })

通过下面一个简单的小例子来感受一下是如何前后端分离进行数据库的增删改查的。

一、创建一个数据库

SET FOREIGN_KEY_CHECKS=0;

DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `student_id` varchar(32) COLLATE utf8_bin NOT NULL,
  `student_name` varchar(32) COLLATE utf8_bin NOT NULL,
  `student_sex` char(4) COLLATE utf8_bin NOT NULL,
  `student_class` varchar(32) COLLATE utf8_bin NOT NULL,
  `student_phone` varchar(64) COLLATE utf8_bin DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

INSERT INTO `student` VALUES ('001', '智慧包', '女', '软件2班', '18866778899');
INSERT INTO `student` VALUES ('002', '皇后娘娘', '男', '软件2班', '18877889900');
INSERT INTO `student` VALUES ('003', '铁根', '女', '软件2班', '18855667788');
INSERT INTO `student` VALUES ('004', '下巴', '男', '软件2班', '18899001122');

二、后端部分

1、创建一个spring初始化项目

选择这个几个dependencies

20200408115939762.png

2、实现数据的增删改查

student.java
package com.test.Entity;
import lombok.Data;

@Data
public class Student {
    private String studentId;
    private String studentName;
    private String studentSex;
    private String studentClass;
    private String studentPhone;
}
studentDao.java
package com.test.dao;
import com.test.Entity.Student;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
public interface StudentDao {

    @Select("select * from student")
    public List<Student> getAll();

    @Insert("insert into student values(#{studentId}, #{studentName}, #{studentSex}, #{studentClass}, #{studentPhone})")
    public int insertStudent(Student student);

    @Select("select * from student where student_id = #{studentId}")
    public Student findById(@Param("studentId") String studentId);

    @Update("update student set student_name = #{studentName}, student_sex = #{studentSex}, student_class = #{studentClass}, student_phone = #{studentPhone} where student_id = #{studentId}")
    public int updateStudent(Student student);

    @Delete("delete from student where student_id = #{studentId}")
    public int deleteStudent(@Param("studentId") String studentId);
}
studentService.java
package com.test.Service;
import com.test.Entity.Student;
import java.util.List;

public interface StudentService {
    public List<Student> getAll();
    public int insertStudent(Student student);
    public Student findById(String studentId);
    public int updateStudent(Student student);
    public int deleteStudent(String studentId);
}
studentServiceImpl.java
package com.test.ServiceImpl;
import com.test.Entity.Student;
import com.test.Service.StudentService;
import com.test.dao.StudentDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentDao studentDao;

    @Override
    public List<Student> getAll() {
        return studentDao.getAll();
    }

    @Override
    public int insertStudent(Student student) {
        return studentDao.insertStudent(student);
    }

    @Override
    public Student findById(String studentId) {
        return studentDao.findById(studentId);
    }

    @Override
    public int updateStudent(Student student) {
        return studentDao.updateStudent(student);
    }

    @Override
    public int deleteStudent(String studentId) {
        return studentDao.deleteStudent(studentId);
    }
}
studentController.java

注意这里的@CrossOrigin注解,可以解决跨域的问题

package com.test.Controller;
import com.test.Entity.Student;
import com.test.Service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@Controller
@CrossOrigin(allowCredentials="true")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @RequestMapping("/getAll")
    @ResponseBody
    public List<Student> getAll(){
        return studentService.getAll();
    }

    @PostMapping("/addStudent")
    @ResponseBody
    public int insertStudent(@RequestBody Student student){
        int row = studentService.insertStudent(student);
        return row;
    }

    @GetMapping("/findById/{studentId}")
    @ResponseBody
    public Student findById(@PathVariable("studentId") String studentId){
        return studentService.findById(studentId);
    }

    @RequestMapping("/updateStudent")
    @ResponseBody
    public int updateStudent(@RequestBody Student student){
        return studentService.updateStudent(student);
    }

    @RequestMapping("/delete/{studentId}")
    @ResponseBody
    public int deleteStudent(@PathVariable("studentId") String studentId){
        return studentService.deleteStudent(studentId);
    }
}
application.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/separate?useUnicode=true&characterEncoding=utf-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456

mybatis.configuration.map-underscore-to-camel-case=true

logging.level.com.test.dao=debug
pom.xml
<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.test</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Separate</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <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.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.6</version>
        </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>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>