天天看点

SpringMVC整合springfox-swagger2构建restful API文档(Maven项目)

1.Swagger 是一款RESTFUL接口的文档在线自动生成的工具,由于在工作中项目也用到这项技术,也在闲余时间,对SpringMVC+swagger2进行了整合,参考了网上的很多文档,不过也花了好一会儿时间才弄出来。以下是个人总结:

2.在你的SpringMVC项目的pom.xml文件中添加以下依赖:

<!--jackson-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.4.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.4.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.4.3</version>
        </dependency>

        <!--springfox的核心jar包-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.4.0</version>
        </dependency>
        <!--springfox-ui的jar包(里面包含了swagger的界面静态文件)-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.4.0</version>
        </dependency>
           

3.创建一个Swagger的配置类,该类必须受Spring管理,必须注入到Spring容器中,本例中使用的@Configuration将该类注入生效,否则无法生效:

package com.mmall.common;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
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;

/**
 * Swagger配置
 */
@Configuration  //将该类注入Spring容器
@EnableWebMvc  //启用MVC
@EnableSwagger2 //启用swagger
public class SwaggerConfig {

   @Bean
   public Docket platformApi() {
	   return new Docket(DocumentationType.SWAGGER_2)
               .select()
               .apis(RequestHandlerSelectors.any())
               .build()
               .apiInfo(apiInfo());
   }

   private ApiInfo apiInfo() {
	   return new ApiInfoBuilder()
			   .contact(new Contact("kang", "https://github.com/ncshub/MMALL.git", "[email protected]"))
               .title("mmall-rest-api")
               .description("MMALL API接口文档")
               .version("1.0")
               .build();
   }

}
           

3.在spring mvc配置dispatcher-servlet.xml(配置文件名字不尽相同)里面加入配置,在springMVC-servlet.xml中配置<mvc:default-servlet-handler />后,会在Spring MVC上下文中定义一个DefaultServletHttpRequestHandler,它会像一个检查员,对进入DispatcherServlet的URL进行筛查,如果发现是静态资源的请求,就将该请求转由Web应用服务器默认的Servlet处理,如果不是静态资源的请求,才由DispatcherServlet继续处理。

<mvc:default-servlet-handler />
           

4.为你的controller层添加一些swagger的注解,我这里只贴了一个接口。

package com.mmall.controller.backend;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
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.mmall.common.Const;
import com.mmall.common.ServiceResponse;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;

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


@Controller
@RequestMapping("/manage/user")
@Api(value = "/manage", description = "manage user",tags = "Manage")
public class UserManagerController {
	
	@Autowired
	private IUserService iUserService;
	
	
	@ApiOperation(value = "管理员登录接口", notes = "提供用户名和密码")
	@RequestMapping(value = "login.do", method = RequestMethod.POST,consumes="text/html;charset=utf-8",produces="application/json;charset=utf-8")
	@ResponseBody
	public ServiceResponse<User> login(
			@ApiParam(value = "用户名", required = true)@RequestParam("username") String username, 
			@ApiParam(value = "登录密码", required = true)@RequestParam("password") String password, HttpSession session){
		ServiceResponse<User> response = iUserService.login(username, password);
		if (response.isSuccess()) {
			User user = response.getData();
			if (user.getRole() == Const.Role.ROLE_ADMIN) {
				session.setAttribute(Const.CURRENT_USER, user);
				return response;
			}else {
				return ServiceResponse.createByErrorMessage("不是管理员,无法登录");
			}
		}
		return response;
	}
	
}
           

5.本人遇到的坑属于以下内容(希望大家别再踩同样的坑),由于在web.xml中配置SpringMvc的servlet映射时,拦截的路径配置成了<url-pattern>*.do</url-pattern>导致死活加载不出来swagger文档,出现了以下情况,有页面,但是什么也加载不出来:

<servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
     </servlet>
     <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.do</url-pattern>
     </servlet-mapping>
           
SpringMVC整合springfox-swagger2构建restful API文档(Maven项目)

6.所以将其改为以下配置后<url-pattern>/</url-pattern>,再重启项目,打开http://localhost:8080/mmall/swagger-ui.html   就看到成功了,大功告成

<servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
           
SpringMVC整合springfox-swagger2构建restful API文档(Maven项目)

继续阅读