随着互联网技术的发展和移动应用的广泛应用,要求前端开发必须与后端开发分离,实施工程化开发模式。Ajax技术使所有服务器端数据都可以通过异步交互获取。只要能从后台取得一个规范定义的RESTful风格接口,前后两端就可以并行完成项目开发任务。网页有网页的处理方式,APP有APP的处理方式,但无论哪种前端,所需的数据基本相同,后端仅需开发一套逻辑对外提供数据即可。
统一的接口是RESTful风格的核心内容。RESTful定义了Web API接口的设计风格,非常适用于前后端分离的应用模式中。RESTful接口约束包含的内容有资源识别、请求动作和响应信息,即通过URL表明要操作的资源,通过请求方法表明要执行的操作,通过返回的状态码表明这次请求的结果。
修改测试代码时,无需手动重启项目
在前后端分离架构下,后端设计成 RESTful API的数据接口。接口中有时返回数据,有时又没有,还有的会出错,也就是返回结果不一致,客户端调用时非常不方便。实际开发中,一般设置统一响应体返回值格式,通过修改响应返回的JSON数据,让其带上一些固有的字段,如下所示:
{"code": 600,"msg": "success","data": {"id": 1,"uname": "cc""password":111}
}
在实际开发中,常用Swagger-API接口文档自动生成工具,帮助项目自动生成和维护接口文档。Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格
的 Web 服务,它具有以下特点:
在pom.xml中加入Swagger依赖
io.springfox springfox-swagger2 2.9.2 io.springfox springfox-swagger-ui 2.9.2
@Api注解:标记当前Controller的功能
@ApiOperation注解:用来标记一个方法的作用
@ApiImplicitParam注解:用来描述一个参数
pom.xml
4.0.0 org.springframework.boot spring-boot-starter-parent 2.7.5 com.example week11_20201000000 0.0.1-SNAPSHOT week11_20201000000 week11_20201000000 1.8 org.springframework.boot spring-boot-starter-web org.mybatis.spring.boot mybatis-spring-boot-starter 2.2.2 com.mysql mysql-connector-j runtime org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test io.springfox springfox-swagger2 2.9.2 io.springfox springfox-swagger-ui 2.9.2 src/main/java **/*.xml src/main/resources **.* org.springframework.boot spring-boot-maven-plugin org.projectlombok lombok
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
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
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
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
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() {}}
GET
http://localhost:8080/student
GET
http://localhost:8080/student/20201001111
POST
http://localhost:8080/student
PUT
http://localhost:8080/student
DELETE
http://localhost:8080/student/20201005590
POST
http://localhost:8080/studentException
访问:http://localhost:8080/swagger-ui.html,即可看到接口文档信息