[java]SpringMVC+Swagger實現自動接口

項目使用SpringMVC+Mavenjavascript

1.在站點項目的POM文件中引入Swagger的jar包css

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>4.1.4.RELEASE</spring.version>
        <jackson.version>2.5.0</jackson.version>
</properties>

<!-- Swagger -->
         <dependency>
            <groupId>com.mangofactory</groupId>
            <artifactId>swagger-springmvc</artifactId>
            <version>0.9.5</version>
        </dependency>
 
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</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-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <!-- Swagger -->

2.添加自定義MySwaggerConfig類文件,個人寫和Controller平級的Common中html

下面上MySwaggerConfig的代碼實現java

 1 package com.etaofinance.wap.common;
 2 import org.springframework.beans.factory.annotation.Autowired;
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.context.annotation.ComponentScan;
 5 import org.springframework.context.annotation.Configuration;
 6  
 7 
 8 
 9 
10 import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
11 import com.mangofactory.swagger.models.dto.ApiInfo;
12 import com.mangofactory.swagger.plugin.EnableSwagger;
13 import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
14 @Configuration
15 @EnableSwagger
16 public class MySwaggerConfig {
17     private SpringSwaggerConfig springSwaggerConfig;
18     /**
19      * Required to autowire SpringSwaggerConfig
20      */
21     @Autowired
22     public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig)
23     {
24         this.springSwaggerConfig = springSwaggerConfig;
25     }
26  
27     /**
28      * Every SwaggerSpringMvcPlugin bean is picked up by the swagger-mvc
29      * framework - allowing for multiple swagger groups i.e. same code base
30      * multiple swagger resource listings.
31      */
32     @Bean
33     public SwaggerSpringMvcPlugin customImplementation()
34     {
35          return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
36          .apiInfo(apiInfo())
37          .includePatterns(".*?");
38     }
39  
40     private ApiInfo apiInfo()
41     {
42         ApiInfo apiInfo = new ApiInfo(
43                 "易淘金服-衆籌", 
44                 "易淘金服衆籌Wap接口",
45                 "My Apps API terms of service", 
46                 "ru.huaxiao@etao.cn", 
47                 "My Apps API Licence Type",
48                 "http:100.com");
49         return apiInfo;
50     }
51 }

ApiInfo 定義的是頁面顯示的一些信息,這點我就不刪除了jquery

 

3.xxx-servlet.xml配置文件中添加註入節點web

      <!-- Swagger 注入配置 -->
    <bean class="com.etaofinance.wap.common.MySwaggerConfig">
    </bean> 
    <!-- Swagger 注入配置 -->

4.在Controll上添加註解spring

/**
     * 項目列表接口(WAP)
     * @param req
     * @return
     */
    @RequestMapping("projectlist")
    @ResponseBody
    @ApiOperation(value = "項目接口;列表", httpMethod = "POST", 
    consumes="application/json;charset=UFT-8",produces="application/json;charset=UFT-8",
    notes = "項目接口列表")
    public  PagedResponse<ProjectModel> projectlist(@RequestBody PagedProjectReq req) {
        return projectService.getProjectList(req);
    }

說明:
其中@ApiOperation和@ApiParam爲添加的API相關注解,個參數說明以下:
@ApiOperation(value = 「接口說明」, httpMethod = 「接口請求方式」, response = 「接口返回參數類型」, notes = 「接口發佈說明」);
@ApiParam(required = 「是否必須參數」, name = 「參數名稱」, value = 「參數具體描述」
)json

其餘參數可參考官方文檔 api

5:添加Swagger UI配置

在GitHub上下載SwaggerUI項目,將dist下全部內容拷貝到本地項目webapp下面,結果目錄以下圖mvc

webapp目錄結構

注意:這是我不推薦的一種方式,我建議添加一個Action而後經過配置改變什麼時候該頁面能夠被訪問

下面說說個人寫法

5.1.將Swagger所須要的文件放入資源的文件夾

5.2.添加一個CommonController 和SwaggerAction

package com.etaofinance.wap.controllor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.etaofinance.api.service.inter.IMemberService;
import com.etaofinance.entity.common.HttpResultModel;
import com.etaofinance.entity.req.SendCodeReq;



@Controller
@RequestMapping("common")
public class CommonController {
    @Autowired
    IMemberService memberService;    
    
    @RequestMapping("/swagger")
    public ModelAndView suggAdd() {
        ModelAndView model = new ModelAndView("common/swagger");
        return model;
    }
}

5.3添加jsp.承載頁面

<%@page import="java.util.stream.Collectors"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="com.etaofinance.core.util.PropertyUtils"%>
<%
    String basePath = PropertyUtils.getProperty("java.wap.url");
%>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Swagger UI</title>
  <link rel="icon" type="image/png" href="<%=basePath%>/swagger/images/favicon-32x32.png" sizes="32x32" />
  <link rel="icon" type="image/png" href="<%=basePath%>/swagger/images/favicon-16x16.png" sizes="16x16" />
  <link href='<%=basePath%>/swagger/css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
  <link href='<%=basePath%>/swagger/css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
  <link href='<%=basePath%>/swagger/css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
  <link href='<%=basePath%>/swagger/css/reset.css' media='print' rel='stylesheet' type='text/css'/>
  <link href='<%=basePath%>/swagger/css/print.css' media='print' rel='stylesheet' type='text/css'/>
  <script src='<%=basePath%>/swagger/lib/jquery-1.8.0.min.js' type='text/javascript'></script>
  <script src='<%=basePath%>/swagger/lib/jquery.slideto.min.js' type='text/javascript'></script>
  <script src='<%=basePath%>/swagger/lib/jquery.wiggle.min.js' type='text/javascript'></script>
  <script src='<%=basePath%>/swagger/lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
  <script src='<%=basePath%>/swagger/lib/handlebars-2.0.0.js' type='text/javascript'></script>
  <script src='<%=basePath%>/swagger/lib/js-yaml.min.js' type='text/javascript'></script>
  <script src='<%=basePath%>/swagger/lib/lodash.min.js' type='text/javascript'></script>
  <script src='<%=basePath%>/swagger/lib/backbone-min.js' type='text/javascript'></script>
  <script src='<%=basePath%>/swagger/swagger-ui.js' type='text/javascript'></script>
  <script src='<%=basePath%>/swagger/lib/highlight.9.1.0.pack.js' type='text/javascript'></script>
  <script src='<%=basePath%>/swagger/lib/highlight.9.1.0.pack_extended.js' type='text/javascript'></script>
  <script src='<%=basePath%>/swagger/lib/jsoneditor.min.js' type='text/javascript'></script>
  <script src='<%=basePath%>/swagger/lib/marked.js' type='text/javascript'></script>
  <script src='<%=basePath%>/swagger/lib/swagger-oauth.js' type='text/javascript'></script>

  <!-- Some basic translations -->
  <!-- <script src='lang/translator.js' type='text/javascript'></script> -->
  <!-- <script src='lang/ru.js' type='text/javascript'></script> -->
  <script src='<%=basePath%>/swagger/lang/zh-cn.js' type='text/javascript'></script>

  <script type="text/javascript">
    $(function () {
      var url = window.location.search.match(/url=([^&]+)/);
      if (url && url.length > 1) {
        url = decodeURIComponent(url[1]);
      } else {
        url = "<%=basePath%>/api-docs";
      }

      hljs.configure({
        highlightSizeThreshold: 5000
      });

      // Pre load translate...
      if(window.SwaggerTranslator) {
        window.SwaggerTranslator.translate();
      }
      window.swaggerUi = new SwaggerUi({
        url: url,
        dom_id: "swagger-ui-container",
        supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'],
        onComplete: function(swaggerApi, swaggerUi){
          if(typeof initOAuth == "function") {
            initOAuth({
              clientId: "your-client-id",
              clientSecret: "your-client-secret-if-required",
              realm: "your-realms",
              appName: "your-app-name",
              scopeSeparator: ",",
              additionalQueryStringParams: {}
            });
          }

          if(window.SwaggerTranslator) {
            window.SwaggerTranslator.translate();
          }
        },
        onFailure: function(data) {
          log("Unable to Load SwaggerUI");
        },
        docExpansion: "none",
        jsonEditor: false,
        defaultModelRendering: 'schema',
        showRequestHeaders: false
      });

      window.swaggerUi.load();

      function log() {
        if ('console' in window) {
          console.log.apply(console, arguments);
        }
      }
  });
  </script>
</head>

<body class="swagger-section">
<div id='header'>
  <div class="swagger-ui-wrap">
    <a id="logo" href="http://swagger.io"><img class="logo__img" alt="swagger" height="30" width="30" src="<%=basePath%>/swagger/images/logo_small.png" /><span class="logo__title">swagger</span></a>
    <form id='api_selector'>
      <div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div>
      <div id='auth_container'></div>
      <div class='input'><a id="explore" class="header__btn" href="<%=basePath%>/swagger#" data-sw-translate>Explore</a></div>
    </form>
  </div>
</div>
<div id="message-bar" class="swagger-ui-wrap" data-sw-translate>&nbsp;</div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</body>
</html>

注意加紅的字體的地方.這裏是Swagger的路徑.

6.讓你的站點跑起來吧!!最後結果以下

 

最後 看看攔截器的代碼

public class AuthInteceptor extends HandlerInterceptorAdapter {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String basePath =PropertyUtils.getProperty("java.wap.url");
        String IsOpenSwagger=PropertyUtils.getProperty("IsOpenSwagger");
        if(request.getServletPath().equals("/common/swagger")&&IsOpenSwagger.equals("0"))
        {//驗證是否開啓Swagger  1 開啓 0未開啓 不容許訪問
            response.sendRedirect(basePath);
            return false;
        }
}

 演示參數中的時間類型有問題 ,修改源碼格式化

修改swagger-ui.js

'use strict';
//////
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //
        "H+": this.getHours(), //小時 
        "m+": this.getMinutes(), //
        "s+": this.getSeconds(), //
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

function representYamlTimestamp(object,fmt /*, style*/) {
      //return object.toISOString();
    var res="";
    if(fmt==undefined){
        res= object.Format("yyyy-MM-dd HH:mm:ss"); 
    }else{
        res= object.Format(fmt);
    }
    //alert(res);
    return res;
};
/////////////////////
$(function() {
相關文章
相關標籤/搜索