SpringMVC中使用Swagger2整合

1.关于 Swagger

Swagge的目标是为REST APIs 定义一个标准的,与语言无关的接口,使人和计算机在看不到源码或者看不到文档或者
不能通过网络流量检测的情况下 能发现和理解各种服务的功能。当服务通过Swagger定义,消费者就能与远程的服务
互动通过少量的实现逻辑。类似于低级编程接口,Swagger去掉了 调用服务时的很多猜测

Swagger能成为最受欢迎的REST APIs文档生成工具之一,有以下几个原因:

  • Swagger 可以生成一个具有互动性的API控制台,开发者可以用来快速学习和尝试API。
  • Swagger 可以生成客户端SDK代码用于各种不同的平台上的实现。
  • Swagger 文件可以在许多不同的平台上从代码注释中自动生成。
  • Swagger 有一个强大的社区,里面有许多强悍的贡献者。

2.搭建基于maven的springmvc项目

2.1.创建maven项目

具体细节和过程可以参考之前的文章“搭建SpringMVC+Spring3+Hibernate4框架的maven项目”的前段部分

2.2.集成springmvc:

我们在web.xml文件里面添加下面的配置:

2.2.1配置监听器

<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<listener>
	<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>

2.2.2 配置过滤器,解决POST乱码问题


<filter>
    <filter-name>encoding</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>encoding</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

2.2.3配置SpringMVC分发器,拦截所有请求

<servlet>
     <servlet-name>springmvc</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <init-param>
         <param-name>namespace</param-name>
         <param-value>dispatcher-servlet</param-value>
     </init-param>
</servlet>

<servlet-mapping>
     <servlet-name>springmvc</servlet-name>
     <url-pattern>/</url-pattern>
 </servlet-mapping>
我们需要在WEB-INF的根目录下新建一个dispatcher-servlet.xml文件

2.2.4编写dispatcher-servlet.xml

配置如下:
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"  
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd    
      http://www.springframework.org/schema/context    
      http://www.springframework.org/schema/context/spring-context-3.2.xsd    
      http://www.springframework.org/schema/mvc    
      http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">  
    <!-- 注解扫描包 -->  
    <context:component-scan base-package="com.pengtu.swagger.controller" />  
    <!-- 开启mvc注解 -->  
    <mvc:annotation-driven ></mvc:annotation-driven>
    <!-- 静态资源过滤 -->
    <mvc:resources location="/resources/" mapping="/resources/**"/>

  	<!-- JSP视图解析器-->
    <bean id="viewResolver"  
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/views/"></property>  
        <property name="suffix" value=".jsp"></property>  
        <!--  prefix和suffix:查找视图页面的前缀和后缀(前缀[逻辑视图名]后缀),
        	   比如传进来的逻辑视图名为hello,则该该jsp视图页面应该存放在“WEB-INF/views/hello.jsp” -->
    </bean>  
    
     <!-- 上传文件时需要做的配置 -->  
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
      <property name="defaultEncoding" value="utf-8" />
      <property name="maxUploadSize" value="10485760000" />
      <property name="maxInMemorySize" value="40960" />
   </bean>
   
</beans>  

如果现在启动的话 会报错: 缺少applicationContext.xml文件
Could not open ServletContext resource [/WEB-INF/applicationContext.xml]

它说我们在WEB-INF下面少了一个applicationContext.xml 这个文件,原来,我们少了对SpringBean工厂的配置,它的意思就是说,我们要规定一下,在Spring容器启动的时候,需要自动加载哪些东西?
于是,我们把 applicationContext.xml 加上

2.2.5  添加 applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
  http://www.springframework.org/schema/beans/spring-beans.xsd  
  http://www.springframework.org/schema/aop   
  http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
  http://www.springframework.org/schema/tx   
  http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
  http://www.springframework.org/schema/context   
  http://www.springframework.org/schema/context/spring-context-4.0.xsd
  http://www.springframework.org/schema/util   
  http://www.springframework.org/schema/util/spring-util-4.0.xsd
  ">

</beans>
启动没问题

3.集成swagger

 3.1 引入swagger相关包-- pom.xml配置

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

 3.2 dispatcher-servlet.xml中添加映射静态的配置

<mvc:default-servlet-handler />

 3.3 创建swagger2的配置类

package com.pengtu.swagger.utils;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableSwagger2 //使swagger2生效  
@ComponentScan(basePackages = {"com.pengtu.swagger.controller"}) //需要扫描的包路径  
@Configurable //配置注解,自动在本类上下文加载一些环境变量信息  
public class RestApiConfig extends WebMvcConfigurationSupport {

	   @Bean
	    public Docket buildDocket(){
	        return new Docket(DocumentationType.SWAGGER_2)
	                .apiInfo(buildApiInf())
	                .select()       .apis(RequestHandlerSelectors.basePackage("com.pengtu.swagger.controller"))//controller路径
	                .paths(PathSelectors.any())
	                .build();
	    }

	    private ApiInfo buildApiInf(){
	        return new ApiInfoBuilder()
	                .title("SpringMVC中使用Swagger2整合")
	                .termsOfServiceUrl("http://blog.csdn.net/zhang289202241")
	                .description("springmvc swagger2")
	                .contact(new Contact("张磊", "http://blog.csdn.net/zhang289202241", "289202241@qq.com"))
	                .build();

	    }
}

 3.4 dispatcher-servlet.xml中添加swagger2配置类

<bean class="com.pengtu.swagger.utils.RestApiConfig" /> 
最后  dispatcher-servlet.xml的内容为:
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"  
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd    
      http://www.springframework.org/schema/context    
      http://www.springframework.org/schema/context/spring-context-3.2.xsd    
      http://www.springframework.org/schema/mvc    
      http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">  
    <!-- 注解扫描包 -->  
    <context:component-scan base-package="com.pengtu.swagger.controller" />  
    <!-- 开启mvc注解 -->  
    <mvc:annotation-driven ></mvc:annotation-driven>
    <!-- 静态资源过滤 -->
    <mvc:resources location="/resources/" mapping="/resources/**"/>
    <mvc:default-servlet-handler /> 
    <bean class="com.pengtu.swagger.utils.RestApiConfig" /> 

  	<!-- JSP视图解析器-->
    <bean id="viewResolver"  
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/views/"></property>  
        <property name="suffix" value=".jsp"></property>  
        <!--  prefix和suffix:查找视图页面的前缀和后缀(前缀[逻辑视图名]后缀),
        	   比如传进来的逻辑视图名为hello,则该该jsp视图页面应该存放在“WEB-INF/views/hello.jsp” -->
    </bean>  
    
     <!-- 上传文件时需要做的配置 -->  
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
      <property name="defaultEncoding" value="utf-8" />
      <property name="maxUploadSize" value="10485760000" />
      <property name="maxInMemorySize" value="40960" />
   </bean>
   
</beans>  

  3.5 创建对应的userController控制类


package com.pengtu.swagger.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pengtu.swagger.entity.User;

@Controller
@RequestMapping("/user")
@Api(value = "user-api", description = "有关于用户的CURD操作")  
public class UserController {
	
	@RequestMapping("/getUser")
	@ApiOperation(value="获取用户信息",notes = "get userinfo",httpMethod = "POST")
	public String getUser(){
		System.out.println("haha");
		return "userInfo";
	}
	
	@ApiResponse(code = 200, message = "success", response = User.class)
    @ApiOperation(value = "获取用户对象", httpMethod = "GET", response = String.class, notes = "根据用户名获取用户对象")
    @RequestMapping(value = "apiGetId", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Object getId(@ApiParam(name = "id", required = true, value = "用户Id") @RequestParam("id") String id) {
		User user = new User();
		user.setUserName("zhanglei");
		user.setPassword("123456");
        return user;
    }
}

项目最后的目录图:

然后运行项目,输入自己的url。
我的url:  http://localhost:8888/swagger/swagger-ui.html
然后就可以看到效果图: 



在controller中涉及到的api相关注解可以参考文章:  http://blog.csdn.net/luohongtucsdn/article/details/74043676

源代码下载: 链接: https://pan.baidu.com/s/1pKYBeVD 密码: ut59

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值