springboot+springdata-jpa+vue+swagger ui2+axios实现前后端分离一套增删改查,分页+解决跨域问题

今天整合了springboot+springdata-jpa+vue+swagger ui2+axios实现前后端分离写了一套增删改查,分页。希望可以给初学者一些帮助。*

后端(idea中SpringBoot项目)

SpringBoot整合Swagger-ui 引入依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

SpringdatajpaApplication类

package com.changan.springdatajpa;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
/*开启swaggerUI 的注解*/
@EnableSwagger2
public class SpringdatajpaApplication {

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

entity(实体类)

package com.changan.springdatajpa.entity;

import lombok.Data;

import javax.persistence.*;

@Data
/*对应数据库中的表*/
@Table(name = "student")
@Entity
public class Student {

    /*Id表示主键  主键有生成策略GenerationType.IDENTITY*/
    /*GenerationType.AUTO*/
    /*Oracle中是没有自动增长的 设置SEQUENCE  使用序列进行增长*/
    /*GeneratedValue 自动增长生成的value值*/
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "name",columnDefinition = "varchar(25) comment '姓名'")
    private String name;

    @Column
    private String sex;

    private Integer gradeId;
}

Service层(实现层)的接口和类

package com.changan.springdatajpa.service;


import com.changan.springdatajpa.entity.Student;
import org.springframework.data.domain.Page;

import java.util.List;

public interface StudentService {

    /**
     * 新增学生信息
     * @param student
     * @return
     */
    Student save(Student student);

    /**
     * 查询所有信息
     * @return
     */
    List<Student> findAll();

    /**
     * 修改学生信息
     * @param student
     * @return
     */
    Student update(Student student);

    /**
     * 删除学生信息
     * @param id
     */
    void delete(Integer id);

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    Page<Student> findByPage(Integer page,Integer size);

    /**
     * 查询前两行
     * @return
     */
    List<Student> findTop();

    /**
     * 根据id查询
     * @param id
     * @return
     */
    Student findById(Integer id);

    /**
     * 根据姓名模糊查询
     * @param name
     * @return
     */
    List<Student> findLikeName(String name);

    /**
     * 根据姓名模糊查询
     * @param name
     * @return
     */
    List<Student> findByName(String name);
}


--------------------- 
作者:丢了微笑该如何释怀 
来源:CSDN 
原文:https://blog.csdn.net/weixin_42236165/article/details/90809519 
版权声明:本文为博主原创文章,转载请附上博文链接!

package com.changan.springdatajpa.service;

import com.changan.springdatajpa.entity.Student;
import org.springframework.data.domain.Page;

import java.util.List;

public interface StudentService {

/**
 * 新增学生信息
 * @param student
 * @return
 */
Student save(Student student);

/**
 * 查询所有信息
 * @return
 */
List<Student> findAll();

/**
 * 修改学生信息
 * @param student
 * @return
 */
Student update(Student student);

/**
 * 删除学生信息
 * @param id
 */
void delete(Integer id);

/**
 * 分页查询
 * @param page
 * @param size
 * @return
 */
Page<Student> findByPage(Integer page,Integer size);

/**
 * 查询前两行
 * @return
 */
List<Student> findTop();

/**
 * 根据id查询
 * @param id
 * @return
 */
Student findById(Integer id);

/**
 * 根据姓名模糊查询
 * @param name
 * @return
 */
List<Student> findLikeName(String name);

/**
 * 根据姓名模糊查询
 * @param name
 * @return
 */
List<Student> findByName(String name);

}

Dao(数据访问层)接口

扫描二维码关注公众号,回复: 6471175 查看本文章
package com.changan.springdatajpa.dao;

import com.changan.springdatajpa.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface StudentDao extends JpaRepository<Student,Integer> {
    /**
     * 查询前两行
     * @return
     */
    List<Student> findTop2By();

    /**
     * 根据姓名模糊查询
     * @param name
     * @return
     */
    List<Student> findByNameContaining(String name);

    //select * form student where name like %name% or sex='' and gradeId = '';
    //List<Student> findByNameContainingOrSexAndGradeId();

    /**
     * 根据姓名模糊查询
     * @param name
     * @return
     */
    @Query(value = "select * from Student where name like concat('%',?,'%') ",nativeQuery = true)
    List<Student> findByName(String name);
}

Controller(控制层)类

package com.changan.springdatajpa.controller;

import com.changan.springdatajpa.dao.StudentDao;
import com.changan.springdatajpa.entity.Student;
import com.changan.springdatajpa.service.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/api")
@Api(value = "swagger ui 注释 api 级别")
//@Controller+@ResponseBody  以json数据进行返回
public class StudentController{

    @Autowired
    private StudentService studentService;

    @Autowired
    private StudentDao studentDao;

    /*restful风格实现*/
    @ApiOperation(value = "新增学生信息",notes = "新增学生信息")
    @PostMapping("/save")
    //@RequestMapping(method = RequestMethod.POST)
    public Student save(@RequestBody Student student){
        return studentService.save(student);
    }


    @ApiOperation(value = "查询学生信息",notes = "查询学生信息")
    @GetMapping("/student")
    public List<Student> findAll(){
        return studentService.findAll();
    }

    @ApiOperation(value = "删除学生信息",notes = "删除学生信息")
    @DeleteMapping("delete")
    public int delete(Integer id){
        try {
            studentService.delete(id);
            return 1;
        } catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    @ApiOperation(value = "修改学生信息",notes = "修改学生信息")
    @PutMapping("/update")
    public Student update(@RequestBody Student student){
        return studentService.update(student);
    }

    @ApiOperation(value = "分页查询学生信息",notes = "分页查询学生信息")
    @GetMapping("/findByPage")
    public Page<Student> findByPage(Integer page,Integer size){
        Page<Student> students = studentService.findByPage(page, size);
        return students;
    }

    @ApiOperation(value = "查询前两行学生信息",notes = "查询前两行学生信息")
    @GetMapping("/findtop")
    public List<Student> findTop(){
        return studentService.findTop();
    }

    @ApiOperation(value = "根据Id查询学生信息",notes = "根据Id查询学生信息")
    @GetMapping("/findById")
    public Student findById(Integer id){
        return studentService.findById(id);
    }

    @ApiOperation(value = "根据姓名查询学生信息",notes = "根据Id查询学生信息")
    @GetMapping("/findLikeName")
    public List<Student> findLikeName(String name){
        return studentService.findLikeName(name);
    }

    @ApiOperation(value = "根据姓名查询学生信息",notes = "根据Id查询学生信息")
    @GetMapping("/findByName")
    public List<Student> findByName(String name){
        return studentService.findByName(name);
    }
}

config包

SwaggerConfig类

package com.changan.springdatajpa.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.changan.springdatajpa.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2实现前后端分离开发")
                .description("此项目只是练习如何实现前后端分离开发的小Demo")
                .termsOfServiceUrl("https://blog.csdn.net/ca1993422")
                .contact("宋政宏")
                .version("1.0")
                .build();
    }
}

运行前往https://swagger.io/tools/swagger-ui/ Swagger官网
在这里插入图片描述
访问
在这里插入图片描述
使用其一种方法测试(此处选择delete删除)
在这里插入图片描述
在这里插入图片描述
成功!
在这里插入图片描述

前端

导入vue.js,axios.js

在这里插入图片描述
进入BootCDN官网:https://www.bootcdn.cn/ 查找vue.js网络路径。
进入Axios文档 https://www.kancloud.cn/yunye/axios/234845 查找axios.js网络路径。

<!-- 通过CDN引入Vue.js -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 通过CDN引入axios -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
、

js代码

<script type="text/javascript">
			var app = new Vue({
				el: '#app',
				data: {
					student: {
						id: '',
						name: '',
						sex: '',
						gradeId: ''
					},
					students: []
				},
				methods: {
					/* findAll: function(page) {
						var _this = this;
						axios.get('http://localhost:8082/api/findByPage',{
							params:{
								page : page,
								size : '3'
							}
						})
							.then(function(response) {
								_this.students = response.data;
							})
							.catch(function(error) {
								console.log(error);
							});
					}, */
					//分页查询
					findByPage:function(page,size){
						axios.get('http://localhost:8082/api/findByPage', {
								params: {
										page:page,
										size:size,
									}
								})
							.then((response) => {
								this.students = response.data;
							})
							.catch(function(error) {
								console.log(error);
							});
					},
					//调用分页查询方法
					pgup:function(page){
						this.findByPage(page,2);
					},
					//新增和修改信息
					Save: function(page) {
						var _this = this;
						var student = JSON.stringify(_this.student)
						if (student.id != null && student.id != '') { //修改
							axios.put('http://localhost:8082/api/update', student, {
									headers: {
										"Content-Type": "application/json;charset=utf-8" //头部信息
									}
								})
								.then(function(response) {
									//保存完之后查询所有的信息
											this.cleanstudent();
										this.pgup(page)
								})
								.catch(function(error) {
									console.log(error);
								});
						} else { //新增
							axios.post('http://localhost:8082/api/save', student, {
									headers: {
										"Content-Type": "application/json;charset=utf-8" //头部信息
									}
								})
								.then(function(response) {
									//保存完之后查询所有的信息
									if (_this.student.id != null) {
										_this.student.id = null;
									}
									this.cleanstudent();
										this.pgup(page)
								})
								.catch(function(error) {
									console.log(error);
								});
						}
					},
					//删除信息
					Delete: function(id,page) {
						var _this = this;
						axios.delete('http://localhost:8082/api/delete', {
								params: {
									 id: id
								}
							})
							.then(function(response) {
								this.cleanstudent();
								this.pgup(page)
							})
							.catch(function(error) {
								console.log(error);
							});
					},
					Edit: function(student) {
						this.student = student;
					},
					cleanstudent:function(){
						this.student.id = null;
						this.student.name = null;
						this.student.sex = null;
						this.student.gradeId = null;
					}
				},
				//创建
				created: function() { //创建vue对象的时候自动调用查询所有的方法
					this.findByPage(0,2);
				}
			})
		</script>

html代码

<div id="app">
			<table border="1" cellspacing="0" cellpadding="5">
				<tr>
					<th>编号</th>
					<th>姓名</th>
					<th>性别</th>
					<th>年级</th>
					<th>操作</th>
				</tr>
				<template v-for="student in students.content">
					<tr>
						<td>{{student.id}}</td>
						<td>{{student.name}}</td>
						<td>{{student.sex}}</td>
						<td>{{student.gradeId}}</td>
						<td>
							<a href="#" @click="Delete(student.id,students.number)">删除</a>
							<a href="#" @click="Edit(student)">编辑</a>
						</td>
					</tr>
				</template>
					<template>
					<tr>
						<td><a href="#" @click="pgup(0)">首页</a></td>
						<td><a href="#" @click="pgup(students.number-1)" v-if="students.number>0">上一页</a></td>
						<td><a href="#" @click="pgup(students.number+1)" v-if="students.number<students.totalPages-1">下一页</a></td>
						<td><a href="#" @click="pgup(students.totalPages-1)">尾页</a></td>
						<td>当前页<label>{{students.number+1}}</label></td>
					</tr>
				</template>
				<template>
					<tr>
						<td><input type="text" placeholder="不需要自己填充" readonly="readonly" v-model="student.id" /></td>
						<td><input type="text" placeholder="请输入用户名" v-model="student.name" /></td>
						<td><input type="text" placeholder="请输入性别" v-model="student.sex" /></td>
						<td><input type="text" placeholder="请输入年级" v-model="student.gradeId" /></td>
						<td>
							<button type="button" @click="Save(students.totalPages-1)">保存</button>
						</td>
					</tr>
				</template>
			</table>
		</div>
 </div>

运行项目测试会发现出现一个angularjs flask跨域问题 XMLHttpRequest cannot load. No 'Access-Control-Allow-Origin’的错误
在这里插入图片描述
简单的处理方式是再后端idea中的SpringBoot项目config包下加一个WebMvcConfig.java类

WebMvcConfig.java代码

package com.changan.springdatajpa.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    //ngnix反响代理实现跨域
    //ngnix负载均衡   单点故障   数据库单点故障  容灾
    //redis  主从复制  投票


    //跨域配置
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            //重写父类提供的跨域请求处理的接口
            public void addCorsMappings(CorsRegistry registry) {
                //添加映射路径
                registry.addMapping("/**")
                        //放行哪些原始域
                        .allowedOrigins("*")
                        //是否发送Cookie信息
                        .allowCredentials(true)
                        //放行哪些原始域(请求方式)
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        //放行哪些原始域(头部信息)
                        .allowedHeaders("*")
                        //暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
                        .exposedHeaders("Header1", "Header2");
            }
        };
    }
}

再运行项目就成功了!
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44591832/article/details/90815124