springMVC集成swagger

springMVC集成swagger

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务.是一个管理接口的框架,通过注解的方式、网页的形式自动帮我们生成接口相关的信息,相比以前文档的方式撰写的接口,swagger更加便捷、高效,省力。
springMVC集成swagger步骤如下:
1、在pom.xml文件中添加swagger2的依赖包

<!-- Jackson  2.5.1 -->
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-core</artifactId>
	<version>${jackson.version}</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>${jackson.version}</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-annotations</artifactId>
	<version>${jackson.version}</version>
</dependency>  

<!--swagger-->
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.9.2</version>
</dependency>
<!--swagger-ui是提供API接口页面展示的-->
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.9.2</version>
</dependency>

2、创建swagger2的配置文件

package com.itic.appbase.applications.swagger.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@EnableWebMvc
@ComponentScan(basePackages = {"com.itic.appbase.applications.sys.swagger.test"}) // 扫描路径
public class Swagger2Config {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("swagger2")
                .description("swagger2")
                .termsOfServiceUrl("http://192.168.235.1:8080/")
                .version("1.0")
                .build();
    }

}

3、springMVC.xml配置

<!-- 重要!配置swagger资源不被拦截 -->
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/" />
<!-- 重要!将你的Swagger2Config配置类注入 -->
<bean id="swagger2Config" class="com.itic.appbase.applications.swagger.config.Swagger2Config"/>

4、控制类

package com.itic.appbase.applications.sys.swagger.test;

import com.itic.appbase.applications.sys.role.persistence.model.Role;
import com.itic.appbase.applications.sys.role.persistence.model.RoleExample;
import com.itic.appbase.applications.sys.role.persistence.model.RoleExample.Criteria;
import com.itic.appbase.applications.sys.role.service.RoleService;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.ValueHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 角色管理
 * <p>
 * Company: itic
 * </p>
 * 
 * @author: shijun
 * @date: 2015年5月13日 上午9:21:44
 * @version: V1.0
 */
@RestController
@RequestMapping(value =  "/swagger" )
@Api(value = "角色信息", description = "角色信息")
public class RoleControllerSwagger
        extends BaseController {
    @Autowired
    private RoleService roleService;
    // 返回属性黑名单
    private static String[] ignoreProperties = new String[] { "createUser" };

    /**
     * 添加角色并同步更新角色资源表
     *
     * @param role
     * @param resourceIds
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ApiOperation(value = "获取角色信息", notes = "获取角色信息",httpMethod = "POST")
    public Map<String, Object> addRole(Role role, String resourceIds) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String result = ResponseCode.SERVER_ERROR.getCode();

        if (null != role && StringHelper.isNotBlank(role.getName())) {
            result = roleService.addRole(role, resourceIds);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();// 参数不合法
        }
        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }
    /**
     * 数据列表展示
     * 
     * @param role
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @ApiOperation(value = "获取角色信息", notes = "获取角色信息",httpMethod = "GET")
    @ResponseBody
    public Map<String, Object> listRole(Role role, HttpServletRequest request) {
        // 声明返回对象
        Map<String, Object> resultMap = new HashMap<String, Object>();
        // 参数处理
        RoleExample roleExample = new RoleExample();
        // 封装分页参数
        roleExample = this.handlePageQuery(request, roleExample);
        // 封装查询条件
        roleExample = this.queryCondition(role, roleExample);
        // 获取数据
        List<Role> roleList = roleService.list(roleExample);
        // 返回属性处理
        List<Map<String, Object>> resultList = ValueHelper.tranList2MapList(roleList, ignoreProperties);
        // 获取数据总数
        int totalNum = roleService.count(roleExample);
        // 数据返回处理
        resultMap.put(IticConst.DATA, resultList);
        resultMap.put(IticConst.TOTAL_RECORDS, totalNum); // 总记录
        resultMap.put(IticConst.DISPLAY_RECORDS, totalNum);//
        resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
        return resultMap;
    }


    /**
     * 封装查询条件
     * 
     * @param role
     *            查询条件
     * @param roleExample
     */
    private RoleExample queryCondition(Role role, RoleExample roleExample) {
        roleExample.setOrderByClause("create_Time asc");
        // 封装查询条件
        Criteria criteria = roleExample.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE);
        if (null != role && StringHelper.isNotBlank(role.getName())) {// 角色名称
            criteria.andNameLike("%" + role.getName() + "%");
        }
        return roleExample;
    }
}

5、访问

配置完成之后重启服务器,访问地址 http://ip:端口/项目名/swagger-ui.html,如:

http://localhost:8080/ZZ_YJXZPT_war_exploded/swagger-ui.html#/

访问效果图如下
在这里插入图片描述
点击具体的接口展开详情,效果图如下:
在这里插入图片描述
在/swagger/list 接口中输入相关参数,点击Try it out 按钮查看接口的返回值,如下:
在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值