前后端分离实践(二)—— 使用Springboot2.0搭建REST风格的Java后端架构

本文详细介绍了如何使用Springboot2.0搭建REST风格的Java后端架构,涵盖了统一JSON响应格式、集成Swagger2、AOP全局异常处理、Hibernate Validator参数验证、Token安全验证和CORS跨域解决方案。通过这些实践,可以提升API的规范性和安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前后端分离实践系列文章总目录

目录

一、统一的JSON数据返回格式

1、JSON响应结构预览

2、JSON响应结构与Java类的映射

3、添加Springboot-web模块的Maven依赖

4、新建一个Controller类编写JSON响应结构的测试方法

5、测试JSON响应结构

二、集成Swagger2进行在线接口文档维护

1、添加Swagger2的Maven依赖

2、在Springboot中启用Swagger2

3、在config包中添加Swagger2的配置类SwaggerConfig

4、测试Swagger的使用

三、使用AOP进行全局的异常处理

1、在config包中添加一个异常切面配置类ExceptionAspectConfig

2、在ApiController中添加测试异常处理的方法

3、进入swagger-ui页面进行/api/exception接口的测试

四、使用hibernate-validator进行请求参数验证

1、config包中添加一个验证配置类ValidatorConfig

2、dto包中添加一个用户请求参数类UserRequestDTO

3、在ApiController中添加一个测试方法

4、进入swagger-ui页面进行/api/addUser接口的测试

五、使用Token提供安全验证机制

1、新建一个Token异常处理类继承至RuntimeException

2、在全局异常配置类中添加TokenException的配置

3、在annotation包中新建一个Token验证注解UserTokenCheck

4、添加Springboot-AOP的Maven依赖

5、在config包中添加安全检查切面配置类验证用户Token信息

6、在ApiController中添加一个测试方法

7、进入swagger-ui页面进行/api/token接口的测试

六、使用CORS技术解决跨域问题

七、最终的项目结构预览

八、源码地址


一、统一的JSON数据返回格式

1、JSON响应结构预览

使用REST风格实现前后端分离架构,首先需要确定返回的JSON响应结构是统一的,也就是说每个REST请求返回的是相同结构的JSON数据。该JSON响应结构如下:

{

  "code":"000",

  "msg":"OK",

  "data":{}

}

2、JSON响应结构与Java类的映射

为了在架构中映射以上JSON响应结构,我们可以编写一个ApiResponse类与之对应,如下:

/**
 *  统一的JSON格式数据响应类
 */
public class ApiResponse<T> {

    private Integer code;

    private String msg;

    private T data;

    public ApiResponse(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    //getter setter ...
}

3、添加Springboot-web模块的Maven依赖

<!--spring web-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

4、新建一个Controller类编写JSON响应结构的测试方法

在controller包中新建一个ApiController类,内容如下:

import com.mengfei.fbsepjava.pojo.ApiResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class ApiController {

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public ApiResponse<String> helloWorld(){
        return new ApiResponse<String>(9999,"OK","Hello World");
    }
}

 @RestController注解代表整个类中所有方法都会返回JSON格式的数据,相当于在每个方法上加上@ResponseBody注解

5、测试JSON响应结构

启动Springboot项目,直接在浏览器中访问http://localhost:8080/api/hello,访问结果如下图所示:

二、集成Swagger2进行在线接口文档维护

1、添加Swagger2的Maven依赖

<!--swagger-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.6.1</version>
</dependency>

2、在Springboot中启用Swagger2

在Springboot启动器的main方法中添加开启Swagger2的注解@EnableSwagger2

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

@SpringBootApplication
@EnableSwagger2
public class FbsepJavaApplication {
    public static void main(String[] args) {
        SpringApplication.run(FbsepJavaApplication.class, args);
    }
}

3、在config包中添加Swagger2的配置类SwaggerConfig

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //扫描的swagger接口包路径
               .apis(RequestHandlerSelectors.basePackage("com.mengfei.fbsepjava.controller"))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(this.setParameter());//不需要添加全局参数时这一行可以删掉

    }


    //通过参数构造器为swagger添加对header参数的支持,如果不需要的话可以删掉
    private List<Parameter> setParameter(){
        ParameterBuilder ticketP
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值