SpringBoot整合Vue

点击上方 Java老铁,并选择 设为星标

优质文章和资料会及时送达

一、后端部分

1.建库

create database springBoot_vue;

2.建user表

create table user(
    id INT(10) primary key auto_increment,
    userName varchar(10),
    passWord varchar(10)
);

插入一条数据

insert into user(userName, passWord) values ("admin","123456");

3.建student表

create table student(
    id int(10) primary key auto_increment,
    name varchar(10),
    gender varchar(10),
    age int(10)
);

插入一条数据

insert into student(name,gender,age) values ("张无忌","男",50);
insert into student(name, gender, age) values ("赵敏","女",30);
insert into student(name, gender, age) values ("周芷若","女",50);
insert into student(name, gender, age) values ("张三丰","男",100);
insert into student(name, gender, age) values ("赵老六","男",50);
insert into student(name, gender, age) values ("孟三分","男",30);

4.代码实现

4.1启动类

@MapperScan("com.eu.demo.dao")
@SpringBootApplication
public class Application {

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

4.2 application.yml

server:
  port: 8001
spring:
  application:
    name: springBoot-vue #服务名
  datasource: #连接池四大参数
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springBoot_vue?characterEncoding=utf-8&useSSL=false
    username: root
    password: root
    druid:
      initial-size: 1 #初始化连接数
      min-idle: 1 #最小空闲连接
      max-active: 20 #最大活动连接
      test-on-borrow: true #获取连接时测试是否可用
      stat-view-servlet:
        allow: true #监控页面启动
mybatis:
  type-aliases-package: com.eu.demo.pojo  #别名扫描
  mapper-locations: classpath:mapper/*.xml  #加载配置文件
  configuration:
    map-underscore-to-camel-case: true  #开启驼峰式命名
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

4.3 实体类

user类:

package com.eu.demo.pojo;

public class User {

    private Integer id;
    private String userName;
    private String passWord;

    public User(String userName, String passWord) {
        this.userName = userName;
        this.passWord = passWord;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
}

Student类

package com.eu.demo.pojo;

public class Student {

    private Integer id;
    private String name;
    private String gender;
    private Integer age;

    public Student(){

    }

    public Student(String name, String gender, Integer age) {
        this.name = name;
        this.gender = gender;
        this.age = age;
    }

    public Student(Integer id, String name, String gender, Integer age) {
        this.id = id;
        this.name = name;
        this.gender = gender;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

4.4 mapper层

UserMapper

@Repository
public interface UserMapper {

    public User findByUserName(String userName);
}

UserMapper.xml




    

StudentMapper

@Repository
public interface StudentMapper {

    public List getStudents();

    public void deleteStudentById(Integer id);

    public void updateStudent(Student student);

    public Student getStudentsById(Integer id);
}

StudentMapper.xml




    

    
        delete from student where id=#{id}
    

    
        update student
        set name=#{name},
            gender=#{gender},
            age=#{age}
        where id=#{id};
    

    

4.5 service层

UserService

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User login(User user){
        User userDb = userMapper.findByUserName(user.getUserName());
        if (userDb != null && userDb.getPassWord().equals(user.getPassWord())){
            return userDb;
        }
        return null;
    }
}

StudentService

@Service
public class StudentService {
    @Autowired
    private StudentMapper studentMapper;

    public List getStudents(){
        return studentMapper.getStudents();
    }

    public void deleteStudentById(Integer id){
        studentMapper.deleteStudentById(id);
    }

    public void updateStudent(Student student){
        studentMapper.updateStudent(student);
    }

    public Student getStudentsById(Integer id){
        Student student = studentMapper.getStudentsById(id);
        return student;
    }
}

4.6 Controller

UserController

@RestController
@RequestMapping
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public Result login(@RequestParam("username")String username,
                        @RequestParam("password")String password){
        User user = new User(username, password);
        User userDb = userService.login(user);
        if (userDb == null){
            return new Result(false, StatusCode.LOGINERROR,"登录失败");
        }
        return new Result(true,StatusCode.OK,"登陆成功",userDb);
    }
}

StudentController

@RestController
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/getStudents")
    public Result getStudnets(){
        List students = studentService.getStudents();
        return new Result(true, StatusCode.OK,"获取数据成功",students);
    }

    @DeleteMapping("/delete")
    public Result deleteStudentById(@RequestParam("id") Integer id){
        studentService.deleteStudentById(id);
        return new Result(true,StatusCode.OK,"删除成功");
    }

    @PutMapping("/update/{id}")
    public Result updateStudent(@PathVariable Integer id,@RequestBody Student student){
        System.out.println(id);
        studentService.updateStudent(student);
        return new Result(true,StatusCode.OK,"修改成功");
    }

    @GetMapping("/getStudentsById/{id}")
    public Result getStudentsById(@PathVariable Integer id){
        return new Result(true,StatusCode.OK,"查询成功",studentService.getStudentsById(id));
    }
}

4.6 运行调试

http://localhost:8001/getStudents

SpringBoot整合Vue_第1张图片

后端其他调试运行图省略,至此所有后端调试结束

4.7 跨域配置

前后端整合之后会出现跨域问题,跨域问题既可以在前端添加配置解决,也可以在后端解决,在这里,我们直接在后端添加配置

CorsConfig类

@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1
        corsConfiguration.addAllowedHeader("*"); // 2
        corsConfiguration.addAllowedMethod("*"); // 3
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4
        return new CorsFilter(source);
    }
}

项目结构图

SpringBoot整合Vue_第2张图片

二、前端部分

1.使用脚手架创建项目(这里使用的是脚手架4)

vue create 项目名

注意:项目名不能出现大写

2.运行

npm run serve

3.配置路由

import Vue from "vue"
import VueRouter from "vue-router"
import HelloWorld from "../components/HelloWorld";
import Login from "../components/Login";
import StudentList from "../components/StudentList";


Vue.use(VueRouter)

const routes=[
    {
        path: "/",
        redirect: "/login"
    },
    {
        path: "/hello",
        component: HelloWorld
    },
    {
        path: "/login",
        component: Login
    },
    {
        path:"/studentList",
        component:StudentList
    }
]

const router=new VueRouter({
    mode:"history",
    routes
})

export default router

把路由导入并注册到 main.js.

4.网络请求

使用到了网络请求,先下载axios

npm inst --save asios

将axios挂载到Vue原型上

Vue.prototype.$http=axios;

配置baseURL

axios.defaults.baseURL="http://127.0.0.1:8001/"

5.登录模板以及实现

Login.vue





登录成功之后跳转到HelloWorld.vue页面

HelloWorld.vue







登录页:

登录成功之后跳转:

SpringBoot整合Vue_第3张图片

控制台打印的数据

SpringBoot整合Vue_第4张图片

6.学生列表模板及实现

StudentList.vue





运行结果

SpringBoot整合Vue_第5张图片

前端源码地址:https://github.com/abandonJava/springBoot_vue.git

关注我

获取更多
Java干货

原创文章

视频资料

技术交流群

你可能感兴趣的:(SpringBoot整合Vue)