IDEA通过springboot搭建swagger接口测试

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zengjin55/article/details/86537003

创建工程项目

  • 使用IDEA创建一个Spring Initializr工程

  • 设置项目域名和项目名

  • 仅选择web依赖,然后下一步直接Finish

  • 修改pom文件,设置swagger相关依赖

设置版本号:

<swagger.version>2.9.2</swagger.version>

设置依赖:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${swagger.version}</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${swagger.version}</version>
</dependency>

  • 新建包和类

选中java右键package,包名:com.essa.config

  • 在config包下新建class:SwaggerConfig
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .pathMapping("/")
                .select()
                .paths(PathSelectors.regex("/.*"))
                .build();
    }
    //设置swagger的一些信息
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("essa测试部接口文档")
                .contact(new Contact("TestGroup","","[email protected]"))
                .description("这是swagger生成的接口文档")
                .version("1.0.0.0")
                .build();
    }
}
  • 修改Application类,添加组件扫描
@SpringBootApplication
@ComponentScan("com.essa")
public class ApitestApplication {

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

模拟接口

  • 在com.essa包下建一个service包,并新建一个类:FirstGetMethod
  • FirstGetMethod类代码:
@RestController
@Api(value = "/",description = "GET接口")
public class FirstGetMethod {
    @RequestMapping(value = "/getInfo",method = RequestMethod.GET)
    @ApiOperation(value = "获得信息接口",httpMethod = "GET")
    public String getInfo(){
        return "这就是你要获得的信息";
    }
}

 

  • 重启服务后,浏览器访问swagger地址,看到刚刚添加的getInfo接口
  • 写一个POST方法接口

在service包中,新建一个FirstPostMethod类

@RestController
@Api(value = "/",description = "POST接口" )
public class FirstPostMethod {
    private  static Cookie cookie;
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ApiOperation(value = "登录接口",httpMethod = "POST")
    public String login(HttpServletResponse response,
                        @RequestParam(value = "userName",required = true) String userName,
                        @RequestParam(value = "password",required = true) String password){

        if(userName.equals("admin") && password.equals("123456")){
            cookie = new Cookie("login","true");
            response.addCookie(cookie);
            return "恭喜你登录成功了!";
        }
        return "用户名或密码错误";
    }
}

 

  • 重启服务,可查看到POST方法

最后附上百度网盘项目代码,提取码:13er

猜你喜欢

转载自blog.csdn.net/zengjin55/article/details/86537003
今日推荐