RESTful+统一响应体+API自动文档的SprinBoot项目
创始人
2024-01-28 10:03:58
0

一、项目要求

  • 实验环境:Idea+mysql+JDK+Tomcat+Maven
  • 将上一周个人作业用 RESTful 接口实现;(上周的SpringBoot+Mybatis+CRUD项目)
  • 配置统一响应体;
  • 配置Swagger,生成API自动文档;
  • 对 RESTful 接口用Postman进行测试,并将测试结果截图;

二、RESTful风格

1、前后端分离

随着互联网技术的发展和移动应用的广泛应用,要求前端开发必须与后端开发分离,实施工程化开发模式。Ajax技术使所有服务器端数据都可以通过异步交互获取。只要能从后台取得一个规范定义的RESTful风格接口,前后两端就可以并行完成项目开发任务。网页有网页的处理方式,APP有APP的处理方式,但无论哪种前端,所需的数据基本相同,后端仅需开发一套逻辑对外提供数据即可

2、RESTful风格

统一的接口是RESTful风格的核心内容。RESTful定义了Web API接口的设计风格,非常适用于前后端分离的应用模式中。RESTful接口约束包含的内容有资源识别、请求动作和响应信息,即通过URL表明要操作的资源,通过请求方法表明要执行的操作,通过返回的状态码表明这次请求的结果。

3、设计规范

  • 协议:统一使用HTTPs协议或者HTTP协议其中一种
  • 域名:应该尽量将API部署在专用域名之下,如 https://xxx.xxx.com;
  • 版本:应该将API的版本号放入URL,如http://www.example.com/app/1.1/foo
  • 路径:只能有名词,不能有动词,而且所用的名词往往与数据库的表名对应,名词应该用复数
  • HTTP动词:GET(SELECT)、POST(INSERT)、PUT(UPDATE)、DELETE(DELETE)
  • 过滤信息:补充字段
  • 状态码:
  • 返回结果:code+msg+data(常用)

三、SpringBoot热部署

修改测试代码时,无需手动重启项目
在这里插入图片描述
在这里插入图片描述

四、统一格式的响应体

在前后端分离架构下,后端设计成 RESTful API的数据接口。接口中有时返回数据,有时又没有,还有的会出错,也就是返回结果不一致,客户端调用时非常不方便。实际开发中,一般设置统一响应体返回值格式,通过修改响应返回的JSON数据,让其带上一些固有的字段,如下所示:

{"code": 600,"msg": "success","data": {"id": 1,"uname": "cc""password":111}
}

五、统一异常处理

请添加图片描述

六、Swagger—API 接口文档自动生成工具

在实际开发中,常用Swagger-API接口文档自动生成工具,帮助项目自动生成和维护接口文档。Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格
的 Web 服务,它具有以下特点:

  • 及时性:接口变更后,Api文档同步自动更新;
  • 规范性:遵守RESTful风格,保证接口的规范性,如接口的地址,请求方式,参
    数及响应格式和错误信息;
  • 一致性:接口信息一致,不会因开发人员拿到的文档版本不一致而导致分歧;
  • 可测性:直接在接口文档上进行测试,可以在线测试Api接口,方便理解业务。

在pom.xml中加入Swagger依赖

io.springfoxspringfox-swagger22.9.2io.springfoxspringfox-swagger-ui2.9.2
@Api注解:标记当前Controller的功能
@ApiOperation注解:用来标记一个方法的作用
@ApiImplicitParam注解:用来描述一个参数

在这里插入图片描述

七、项目完整代码

pom.xml


4.0.0org.springframework.bootspring-boot-starter-parent2.7.5 com.exampleweek11_202010000000.0.1-SNAPSHOTweek11_20201000000week11_202010000001.8org.springframework.bootspring-boot-starter-weborg.mybatis.spring.bootmybatis-spring-boot-starter2.2.2com.mysqlmysql-connector-jruntimeorg.projectlomboklomboktrueorg.springframework.bootspring-boot-starter-testtestio.springfoxspringfox-swagger22.9.2io.springfoxspringfox-swagger-ui2.9.2src/main/java**/*.xmlsrc/main/resources**.*org.springframework.bootspring-boot-maven-pluginorg.projectlomboklombok

application.yml

spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/myschool?serverTimezone=Hongkong?characterEncoding=utf8&serverTimezone=GMT%2B8username: rootpassword: 密码mvc:pathmatch:matching-strategy: ant_path_matchermybatis:mapper-locations: classpath:com/exmaple/mapper/*.xml    #指定sql配置文件的位置type-aliases-package: com.example.pojo      #指定实体类所在的包名configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl   #输出SQL命令

Student.java

package com.example.pojo;import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@NoArgsConstructor //自动生成无参构造函数
@AllArgsConstructor
@ApiModel(description = "学生字段")
public class Student {@ApiModelProperty(value = "学生id",name = "id",example = "20201001111")private Long id;@ApiModelProperty(value = "学生名",name = "sname",example = "张三")private String sname;@ApiModelProperty(value = "专业",name = "dept",example = "软件工程")private String dept;@ApiModelProperty(value = "年龄",name = "age",example = "20")private int age;
}

StudentMapper.java

package com.example.mapper;import com.example.pojo.Student;import java.util.List;
import java.util.Map;public interface StudentMapper {//1public List getAllStudentMap();//2public Student getStudentById(Long id);//3更新用户信息public int updateStudentByDynam(Map mp);//4public int addStudent(Student student);//5public int deleteStudentById(Long id);}

StudentMapper.xml


update studentsname=#{sname},dept=#{dept},age=#{age},id=#{id}where id=#{id}INSERT INTO student SET sname=#{sname},dept=#{dept},age=#{age}DELETE FROM studentwhere id=#{id}

StudentService.java

package com.example.service;import com.example.pojo.Student;import java.io.IOException;
import java.util.List;
import java.util.Map;public interface StudentService {//1public List getAllStudentMap();//2public Student getStudentById(Long id);//3更新用户信息public int updateStudentByDynam(Map mp);//4public int addStudent(Student student);//5public int deleteStudentById(Long id);}

StudentServiceImpl.java

package com.example.service.impl;import com.example.mapper.StudentMapper;
import com.example.pojo.Student;
import com.example.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.io.IOException;
import java.util.List;
import java.util.Map;@Service
public class StudentServiceImpl implements StudentService {@Autowiredprivate StudentMapper studentMapper;//根据id查询@Overridepublic Student getStudentById(Long id){return studentMapper.getStudentById(id);}//根据id修改用户信息@Overridepublic int updateStudentByDynam(Map mp) {return studentMapper.updateStudentByDynam(mp);}@Overridepublic int deleteStudentById(Long id){return studentMapper.deleteStudentById(id);}//查询用户public List getAllStudentMap() {return studentMapper.getAllStudentMap();}public int addStudent(Student student) {return studentMapper.addStudent(student);}}

StudentController.java

package com.example.controller;import com.example.exception.NotAllowedRegException;
import com.example.pojo.Student;
import com.example.service.StudentService;
import com.example.util.Response;
import com.example.util.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.io.IOException;
import java.util.List;
import java.util.Map;@RestController //=@ResponseBody+@Controller
@Api(tags = "学生管理相关接口")
public class StudentController {@Autowiredprivate StudentService studentService;//    查找所有学生信息@GetMapping("/student")@ApiOperation("查询所有学生信息")public ResponseResult> selectstudentList(){List studentList = studentService.getAllStudentMap();return Response.createOkResp(studentList);}//根据学生id查找对应学生信息@GetMapping("/student/{id}")@ApiOperation("根据id查询学生信息")public ResponseResult selectStudentById(@PathVariable("id") Long id) {Student student = studentService.getStudentById(id);return Response.createOkResp(student);}//ok@PostMapping("/student")@ApiOperation("增加学生信息")public ResponseResult addStudent(Student student) {try {studentService.addStudent(student);return Response.createOkResp("添加成功");} catch (Exception e) {return Response.createFailResp("添加失败");}}@PutMapping("/student")@ApiOperation("更新学生信息")public ResponseResult updateStudentByDynam(@RequestBody Map mp){System.out.println("mp: ");System.out.println(mp);int row = studentService.updateStudentByDynam(mp);System.out.println(row);try {studentService.updateStudentByDynam(mp);return Response.createOkResp("更新成功");} catch (Exception e) {return Response.createFailResp("更新失败");}}//    根据id删除学生记录 okk@DeleteMapping("/student/{id}")@ApiOperation("删除学生信息")public ResponseResult deleteStudentById(@PathVariable("id") Long id){studentService.deleteStudentById(id);return Response.createOkResp();}@PostMapping("/studentException")@ApiOperation("异常处理学生信息")public ResponseResult addStudentException(Student student) throws NotAllowedRegException {//如果添加的用户名是"",则抛出异常if(student.getSname().equals("张三"))throw new NotAllowedRegException();studentService.addStudent(student);return Response.createOkResp();}}

GlobalExceptionHandle.java

package com.example.controller;import com.example.exception.NotAllowedRegException;
import com.example.util.Response;
import com.example.util.ResponseResult;
import com.example.util.StatusCode;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;/**定义一个全局处理异常类,来统一处理各种异常**///@RestController+@ControllerAdvice=@RestControllerAdvice
@RestControllerAdvice
public class GlobalExceptionHandler {//处理异常的方法1.  并确定接收的是哪种类型的异常@ExceptionHandler(Exception.class)public ResponseResult exceptionHandler(Exception e){// 捕获到某个指定的异常,比如是 NotAllowedRegException 类型if(e instanceof  NotAllowedRegException ){//处理结束后 还是要返回统一相应结果类return Response.createFailResp(StatusCode.NOT_ALLOWRD_REG.code,"异常:当前用户不允许注册");}else{//处理其它类型的异常 可以进入到不同的分支return Response.createFailResp();}}/*@ExceptionHandler(NullPointerException.class)public ResponseResult exceptionHandler(NullPointerException e) {}*/
}

SwaggerConfig.java

package com.example.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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;/***  Swagger配置类*/
@Configuration
public class SwaggerConfig {public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.example";public static final String VERSION = "1.0.0";@Beanpublic Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE)).paths(PathSelectors.any()) // 可以根据url路径设置哪些请求加入文档,忽略哪些请求.build();}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("我的第一个项目")   //设置文档的标题.description("*** API 接口文档")   // 设置文档的描述.version(VERSION)   // 设置文档的版本.contact(new Contact("****", "", "***@qq.com")).termsOfServiceUrl("http://***.***.***")   // 配置服务网站,.build();}}

NotAllowedRegException.java

package com.example.exception;import lombok.Data;
import lombok.NoArgsConstructor;/***自定义一个异常类:不能注册*/@Data
@NoArgsConstructor
public class NotAllowedRegException extends  Exception {private int code;private String message;public NotAllowedRegException(String message){super(message);}
}

Response.java

package com.example.util;/*** 定义不同情景下,各种响应体返回的具体值**/
public class Response {private static String SUCCESS="success";private static String FAIL="fail";//创建不同场景下的返回结果对象//1.成功执行,没有要返回的数据public static  ResponseResult createOkResp(){return new ResponseResult(StatusCode.SUCCESS.code,SUCCESS,null);}//2.成功执行,需要返回数据public static  ResponseResult createOkResp(T data){return new ResponseResult(StatusCode.SUCCESS.code,SUCCESS,data);}//3.成功执行,需要返回消息和数据public static  ResponseResult createOkResp(String msg, T data){return new ResponseResult(StatusCode.SUCCESS.code,msg,data);}//4.成功执行,需要消息参数,无数据public static  ResponseResult createOkResp(String msg){return new ResponseResult(StatusCode.SUCCESS.code,msg,null);}//1.失败执行public static  ResponseResult createFailResp(){return new ResponseResult(StatusCode.SERVER_ERROR.code,FAIL,null);}//2.失败执行public static  ResponseResult createFailResp(String msg){return new ResponseResult(500,msg,null);}//3.其它失败执行public static  ResponseResult createFailResp(int code, String msg){return new ResponseResult(code,msg,null);}//4.其他执行public static  ResponseResult createResp(int code, String msg, T data){return new ResponseResult(code,msg,data);}}

ResponseResult.java

package com.example.util;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;/*** 定义响应结果的统一格式,这里定义响应结果由三个要素构成**/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResponseResult {//1.状态码private int code;//2.消息private String msg;//3.返回数据private  T  data;}

StatusCode.java

package com.example.util;/***封装各种状态码*/
public enum StatusCode {//定义枚举项,并调用构造函数//http定义好的状态码SUCCESS(200),SERVER_ERROR(500),URL_NOT_FOUND(404),//自定义的状态码NOT_ALLOWRD_REG(1001);//定义成员变量public int code;//构造方法private StatusCode(int code){this.code=code;}}

Week1120201000000Application.java

package com.example;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;@EnableSwagger2
@SpringBootApplication
@MapperScan(basePackages ="com.example.mapper")
public class Week1120201000000Application {public static void main(String[] args) {SpringApplication.run(Week1120201000000Application.class, args);}}

Week1120201000000ApplicationTests.java

package com.example.week11_20201000000;import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
class Week1120201000000ApplicationTests {@Testvoid contextLoads() {}}

八、运行测试

1、查询所有学生

GET
http://localhost:8080/student

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

2、根据id查询学生信息

GET
http://localhost:8080/student/20201001111

请添加图片描述
请添加图片描述

3、增加学生信息

POST
http://localhost:8080/student

请添加图片描述
请添加图片描述
请添加图片描述请添加图片描述

4、更新学生信息

PUT
http://localhost:8080/student

请添加图片描述

请添加图片描述
请添加图片描述
请添加图片描述

5、删除学生信息

DELETE
http://localhost:8080/student/20201005590

请添加图片描述
请添加图片描述
请添加图片描述

6、异常处理学生信息(如果添加的用户名是"张三",则抛出异常)

POST
http://localhost:8080/studentException

请添加图片描述

7、启动项目,访问API在线文档页面

访问:http://localhost:8080/swagger-ui.html,即可看到接口文档信息

请添加图片描述
请添加图片描述

相关内容

热门资讯

有哪些风口上适合个体创业的项目... 来源:耕叔说钱()作者:耕叔疫情之下,除了少数余粮较多的地主家庭,心理不慌以外。绝大多数人,是受影响...
这几个小生意项目 哪些风口项目... 2、农村合作医疗城市到处有医院,但农村刚好相反。看个病都是非常麻烦的事。所以农村开诊所也是一个非常不...
年轻人最适小本创业好项目首选合... 延伸阅读****'%年轻人%'年青人创业找项目年轻人六大创业好项目1574人年青人敢闯敢拼的精神才是...
小本创业的好项目 小本创业的好...   :野菜种植寻找一块城乡结合处土地,投资种植芦笋,芦蒿,马兰,荠菜等绿色食品,投资小,见效快,市场...
加盟小本创业项目 加盟小本创业... 首页商务服务详情加盟小本创业项目时间:2021-02-加盟小本创业项目一般大的商场***好采取可以保...
小本创业项目,休闲食品加盟! ... 生活水平的普遍提高同时也带动了潜力无限的休闲食品行业的发展,如今休闲食品在国内的年平均增长率达到了2...
个人创业做什么项目好 初涉商业... 关注上方网络营销渠道,学百集网络营销课个人创业做什么项目好?推荐5个小本创业项目!个人创业做什么项目...
适合小本创业五个的好项目 穷人... 如今生活中相信很多人都有一些爱拍照,爱留念的生活习惯,人们对智能设备的使用也已经非常的普及了,有一个...
小本创业15个好项目 小本创业... 为什么穷人多不敢去创业蛋糕创业蛋糕店创业30岁女人创业做什么适合女性创业的大学生适合什么创业毕业生如...
话费小本创业的项目 话费小本创... 小本创业项目:快餐小吃店话费小本创业的项目随着社会压力的增大,很多人没有时间本人做饭,为了工作会选择...