生活如同楼梯般的上上下下

生活如同楼梯般的上上下下

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

项目使用SpringMVC+Maven

1.在站点项目的POM文件中引入Swagger的jar包

<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中

下面上MySwaggerConfig的代码实现

 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 定义的是页面显示的一些信息,这点我就不删除了

 

3.xxx-servlet.xml配置文件中添加注入节点

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

4.在Controll上添加注解

/**
     * 项目列表接口(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 = “参数具体描述”
)

其他参数可参考官方文档

5:添加Swagger UI配置

在GitHub上下载SwaggerUI项目,将dist下所有内容拷贝到本地项目webapp下面,结果目录如下图

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() {

 

posted on 2016-04-12 13:49  生活如同楼梯般的上上  阅读(6607)  评论(1编辑  收藏  举报