springboot + springdata-jpa + vue + swagger ui2 + axios achieve a separation of the front and rear ends CRUD, cross-domain problem solving paging +

Today, the integration of springboot + springdata-jpa + vue + swagger ui2 + axios achieve separation of the front and rear end wrote a CRUD, pagination. I hope you can give some help beginners. *

The back-end (idea in SpringBoot project)

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 (entity class)

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 Layer (Layer implemented) interfaces and classes

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 (Data Access Layer) interfaces

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 (control layer) s

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 package

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();
    }
}

Go to the official website run https://swagger.io/tools/swagger-ui/ Swagger
Here Insert Picture Description
access
Here Insert Picture Description
using its One way to test (here select Delete to delete)
Here Insert Picture Description
Here Insert Picture Description
success!
Here Insert Picture Description

front end

导入vue.js,axios.js

Here Insert Picture Description
Enter BootCDN official website: https://www.bootcdn.cn/ Find vue.js network path.
Axios into the document https://www.kancloud.cn/yunye/axios/234845 find axios.js network path.

<!-- 通过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 code

<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 code

<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>

Run the project Testing reveals the emergence of a angularjs flask cross-domain issues XMLHttpRequest can not load. No 'Access -Control-Allow-Origin' error
Here Insert Picture Description
simple approach is then applied at the backend idea of SpringBoot project config package a class WebMvcConfig.java

WebMvcConfig.java Code

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");
            }
        };
    }
}

And then run the project will be successful!
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/weixin_44591832/article/details/90815124