当前位置:   article > 正文

Spring boot swagger_io.swagger.models.responses

io.swagger.models.responses

swagger用于定义API文档。

好处:

  • 前后端分离开发
  • API文档非常明确
  • 测试的时候不需要再使用URL输入浏览器的方式来访问Controller
  • 传统的输入URL的测试方式对于post请求的传参比较麻烦(当然,可以使用postman这样的浏览器插件)
  • spring-boot与swagger的集成简单

第一步:引入相关的jar包依赖

//swagger
    compile('io.springfox:springfox-swagger2:2.7.0')
    compile('io.springfox:springfox-swagger-ui:2.7.0')
  • 1
  • 2
  • 3

第二步:在application类上加上@EnableSwagger2的注解开启swagger

第三步:UserController

package com.hj.controller;

import com.hj.entity.Result;
import com.hj.entity.User;
import com.hj.repository.UserRepository;
import com.hj.service.UserService;
import com.hj.utils.ResultUtil;
import io.swagger.annotations.*;
import io.swagger.models.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by huangjie on 2017/10/20.
 */
@RestController
@Api("userController相关api")
public class UserController {
    //如何实现在登录前进行统一判读用户是否登录过?不可以再Controller中的构造函数里面判断,因为Spring 程序已启动就把controller类实例化了
    //在http请求的时候不会再实例化了。使用AOP就可以统一判断了
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    @GetMapping("/getlist")
    public List<User> getUser(){
        return userRepository.findAll();
    }

    @ApiOperation("添加用户")
    @ApiImplicitParams({
            //@ApiImplicitParam(paramType="header",name="name",dataType="String",required=true,value="用户的姓名",defaultValue="zhaojigang"),
            @ApiImplicitParam(paramType="query",name="name",dataType="String",required=true,value="用户的姓名",defaultValue="zhaojigang"),
            @ApiImplicitParam(paramType="query",name="pwd",dataType="String",required=true,value="用户的密码",defaultValue="wangna")
    })
    @GetMapping("add")
    public User addUser(@RequestParam("name") String name,@RequestParam("pwd") String pwd){
        User u=new User();
        //u.setId(4);
        u.setName(name);
        u.setPwd(pwd);
        return userRepository.save(u);
    }
    @ApiOperation("获取用户信息")
    @ApiImplicitParams({
                     @ApiImplicitParam(paramType="header",name="name",dataType="String",required=true,value="用户的姓名",defaultValue="zhaojigang"),
          // @ApiImplicitParam(paramType="query",name="name",dataType="String",required=true,value="用户的姓名",defaultValue="zhaojigang"),
                     @ApiImplicitParam(paramType="query",name="pwd",dataType="String",required=true,value="用户的密码",defaultValue="wangna")
                 })
     @ApiResponses({
                     @ApiResponse(code=400,message="请求参数没填好"),
                    @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
                 })
    @RequestMapping(value="/getUser",method= RequestMethod.GET)
     public User getUser(@RequestHeader("name") String name,@RequestParam("pwd") String pwd) {
        System.out.println(name);
        System.out.println(pwd);
                 return userRepository.getUserByNameAndPwd(name,pwd);
             }

    @ApiOperation("添加用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name="user",dataType="User",required=true,value="用户")
    })
    @PostMapping("add2")
    public Result<User> addUser2(@Valid @RequestBody User user, BindingResult bindingResult, Response response){
        if (bindingResult.hasErrors()){
            //response.setHeaders("content-type","application/json;charset=UTF-8");
           // return bindingResult.getFieldError().getDefaultMessage();
           /* Result result=new Result();
            result.setCode(1);
            result.setMessage(bindingResult.getFieldError().getDefaultMessage());
            return  result;*/
           return ResultUtil.error(1,bindingResult.getFieldError().getDefaultMessage());
        }
        /*Result result=new Result();
        result.setCode(0);
        result.setMessage("成功");
        result.setData(userRepository.save(user));
        return result;*/
        return ResultUtil.success(userRepository.save(user));
    }
    @ApiOperation("删除用户")
    @ApiImplicitParams(
            @ApiImplicitParam(paramType="query",name="id",dataType="Integer",required =true ,value = "用户id")
    )
    @RequestMapping(value="/delete",method=RequestMethod.GET)
    public void deleteUser(@RequestParam("id") Integer id){
        userRepository.delete(id);
    }

    @ApiOperation("查询用户")
    @ApiImplicitParams(
            @ApiImplicitParam(paramType="query",name="name",dataType="String",required =true ,value = "用户姓名")
    )
    @RequestMapping(value="/getuser",method=RequestMethod.GET)
    public User getUser(@RequestParam("name") String name){
        return userRepository.getUserByName(name);
    }

    @ApiOperation("根据ID查询用户")
    @ApiImplicitParams(
            @ApiImplicitParam(paramType="query",name="id",dataType="Integer",required =true ,value = "用户ID")
    )
    @RequestMapping(value="/getuserbyid",method=RequestMethod.GET)
    public void getUserById(@RequestParam("id") Integer id) throws Exception{
        userService.getUser(id);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116

说明:

  • @Api:用在类上,说明该类的作用
  • @ApiOperation:用在方法上,说明方法的作用
  • @ApiImplicitParams:用在方法上包含一组参数说明
  • @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面

  • paramType:参数放在哪个地方

    header-->请求参数的获取:@RequestHeader
    query-->请求参数的获取:@RequestParam
    path(用于restful接口)-->请求参数的获取:@PathVariable
    body(不常用)
    form(不常用)
    
    • 1
    • 2
    • 3
    • 4
    • 5

    name:参数名
    dataType:参数类型
    required:参数是否必须传
    value:参数的意思
    defaultValue:参数的默认值

  • @ApiResponses:用于表示一组响应

  • @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息

    code:数字,例如400
    message:信息,例如”请求参数没填好”
    response:抛出异常的类

  • @ApiModel:描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用

  • @ApiImplicitParam注解进行描述的时候)

  • @ApiModelProperty:描述一个model的属性

以上这些就是最常用的几个注解了。

第五步:启动服务,浏览器输入”http://localhost:8080/swagger-ui.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/939843
推荐阅读
相关标签
  

闽ICP备14008679号