swagger下载word

无脑复制粘贴,需要更改的地方已写明。

添加maven依赖

  <dependency>
        <groupId>io.github.swagger2markup</groupId>
        <artifactId>swagger2markup</artifactId>
        <version>1.3.3</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

添加SwaggerConfig文件,更改扫描目录

  @Configuration
  @EnableSwagger2
  public class SwaggerConfig {

      @Bean
      public Docket api() {
          return new Docket(DocumentationType.SWAGGER_2)
                  .select()
                  .apis(basePackage("com.example.demo.controller"))
                  .paths(any())
                  .build();
      }

  }

添加JavaConfig文件

  @Configuration
  public class JavaConfig {

      @Bean
      public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
          TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
          SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                  .loadTrustMaterial(null, acceptingTrustStrategy)
                  .build();
          SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
          CloseableHttpClient httpClient = HttpClients.custom()
                  .setSSLSocketFactory(csf)
                  .build();
          HttpComponentsClientHttpRequestFactory requestFactory =
                  new HttpComponentsClientHttpRequestFactory();
          requestFactory.setHttpClient(httpClient);

          requestFactory.setConnectTimeout(60 * 1000);
          requestFactory.setReadTimeout(60 * 1000);
          RestTemplate restTemplate = new RestTemplate(requestFactory);
          restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
          return restTemplate;
      }
  }

添加ModelAttr实体

  @Data
  public class ModelAttr implements Serializable {

        public String getClassName() {
	      return className;
      }

        public void setClassName(String className) {
	this.className = className;
      }

        public String getName() {
	      return name;
      }

      public void setName(String name) {
	      this.name = name;
      }

      public String getType() {
	      return type;
      }

      public void setType(String type) {
	      this.type = type;
      }

      public Boolean getRequire() {
	      return require;
      }

      public void setRequire(Boolean require) {
	      this.require = require;
      }

      public String getDescription() {
	      return description;
      }

      public void setDescription(String description) {
	      this.description = description;
      }

      public List<ModelAttr> getProperties() {
	      return properties;
      }

      public void setProperties(List<ModelAttr> properties) {
	      this.properties = properties;
      }

      public boolean isCompleted() {
	      return isCompleted;
      }

      public void setCompleted(boolean isCompleted) {
	      this.isCompleted = isCompleted;
      }

      public static long getSerialversionuid() {
	      return serialVersionUID;
      }

      private static final long serialVersionUID = -4074067438450613643L;

      /**
       * 类名
       */
      private String className = StringUtils.EMPTY;
      /**
       * 属性名
       */
      private String name = StringUtils.EMPTY;
      /**
       * 类型
       */
      private String type = StringUtils.EMPTY;
      /**
       * 是否必填
       */
      private Boolean require = false;
      /**
       * 属性描述
       */
      private String description;
      /**
       * 嵌套属性列表
       */
      private List<ModelAttr> properties = new ArrayList<>();

      /**
       * 是否加载完成,避免循环引用
       */
      private boolean isCompleted = false;
  }

添加Request实体

  @Data
  public class Request implements Serializable{

          public String getName() {
	      return name;
      }

          public void setName(String name) {
	      this.name = name;
      }

      public String getType() {
	      return type;
      }

      public void setType(String type) {
	      this.type = type;
      }

      public String getParamType() {
	      return paramType;
      }

      public void setParamType(String paramType) {
	      this.paramType = paramType;
      }

      public Boolean getRequire() {
	      return require;
      }

      public void setRequire(Boolean require) {
	      this.require = require;
      }

      public String getRemark() {
	      return remark;
      }

      public void setRemark(String remark) {
	      this.remark = remark;
      }

      public ModelAttr getModelAttr() {
	      return modelAttr;
      }

      public void setModelAttr(ModelAttr modelAttr) {
	      this.modelAttr = modelAttr;
      }

      /**
       * 参数名
       */
      private String name;

      /**
       * 数据类型
       */
      private String type;
  
      /**
       * 参数类型
       */
      private String paramType;

      /**
       * 是否必填
       */
      private Boolean require;
  
      /**
       * 说明
       */
      private String remark;
  
      /**
       * 复杂对象引用
       */
      private ModelAttr modelAttr;
  }

添加Response实体

  @Data
  public class Response implements Serializable{

      public String getDescription() {
	      return description;
      }

      public void setDescription(String description) {
	      this.description = description;
      }

      public String getName() {
	      return name;
      }

      public void setName(String name) {
	      this.name = name;
      }

      public String getRemark() {
	      return remark;
      }

      public void setRemark(String remark) {
	      this.remark = remark;
      }

      /**
       * 返回参数
       */
      private String description;

      /**
       * 参数名
       */
      private String name;

      /**
       * 备注
       */
      private String remark;
  }

添加Table实体

  @Data
  public class Table {

        public String getTitle() {
	      return title;
      }

     public void setTitle(String title) {
	      this.title = title;
      }

      public String getTag() {
	      return tag;
      }

      public void setTag(String tag) {
	      this.tag = tag;
      }

      public String getUrl() {
	      return url;
      }

      public void setUrl(String url) {
	      this.url = url;
      }

      public String getDescription() {
	      return description;
      }

      public void setDescription(String description) {
	      this.description = description;
      }

      public String getRequestForm() {
	      return requestForm;
      }

      public void setRequestForm(String requestForm) {
	      this.requestForm = requestForm;
      }

      public String getResponseForm() {
	      return responseForm;
      }

      public void setResponseForm(String responseForm) {
	      this.responseForm = responseForm;
      }

      public String getRequestType() {
	      return requestType;
      }

      public void setRequestType(String requestType) {
	      this.requestType = requestType;
      }

      public List<Request> getRequestList() {
	      return requestList;
      }

      public void setRequestList(List<Request> requestList) {
	      this.requestList = requestList;
      }

      public List<Response> getResponseList() {
	      return responseList;
      }

      public void setResponseList(List<Response> responseList) {
	      this.responseList = responseList;
      }

      public String getRequestParam() {
	      return requestParam;
      }

      public void setRequestParam(String requestParam) {
	      this.requestParam = requestParam;
      }

      public String getResponseParam() {
	      return responseParam;
      }

      public void setResponseParam(String responseParam) {
	      this.responseParam = responseParam;
      }

      public ModelAttr getModelAttr() {
	      return modelAttr;
      }

      public void setModelAttr(ModelAttr modelAttr) {
	      this.modelAttr = modelAttr;
      }

      /**
       * 大标题
       */
      private String title;
      /**
       * 小标题
       */
      private String tag;
      /**
       * url
       */
      private String url;

      /**
       * 描述
       */
      private String description;

      /**
       * 请求参数格式
       */
      private String requestForm;

      /**
       * 响应参数格式
       */
      private String responseForm;

      /**
       * 请求方式
       */
      private String requestType;

      /**
       * 请求体
       */
      private List<Request> requestList;

      /**
       * 返回体
       */
      private List<Response> responseList;

      /**
       * 请求参数
       */
      private String requestParam;

      /**
       * 返回参数
       */
      private String responseParam;

      /**
       * 返回属性列表
       */
      private ModelAttr modelAttr = new ModelAttr();
  }

添加WordService

  public interface WordService {

      Map<String,Object> tableList(String swaggerUrl);

      Map<String, Object> tableListFromString(String jsonStr);

      Map<String, Object> tableList(MultipartFile jsonFile);
  }

添加WordServiceImpl

  @Slf4j
  @Service
  public class WordServiceImpl implements WordService {

      @Autowired
      private RestTemplate restTemplate;
      @Override
      public Map<String, Object> tableList(String swaggerUrl) {
          Map<String, Object> resultMap = new HashMap<>();
          try {
              String jsonStr = restTemplate.getForObject(swaggerUrl, String.class);
              resultMap = tableListFromString(jsonStr);
              log.debug(JsonUtils.writeJsonStr(resultMap));
          } catch (Exception e) {
              log.error("parse error", e);
          }
          return resultMap;
      }

      @Override
      public Map<String, Object> tableListFromString(String jsonStr) {
          Map<String, Object> resultMap = new HashMap<>();
          List<Table> result = new ArrayList<>();
          try {
              Map<String, Object> map = getResultFromString(result, jsonStr);
              Map<String, List<Table>> tableMap = result.stream().parallel().collect(Collectors.groupingBy(Table::getTitle));
              resultMap.put("tableMap", new TreeMap<>(tableMap));
              resultMap.put("info", map.get("info"));

              log.debug(JsonUtils.writeJsonStr(resultMap));
          } catch (Exception e) {
              log.error("parse error", e);
          }
          return resultMap;
      }

      @Override
      public Map<String, Object> tableList(MultipartFile jsonFile) {
          Map<String, Object> resultMap = new HashMap<>();
          List<Table> result = new ArrayList<>();
          try {
              String jsonStr = new String(jsonFile.getBytes());
              resultMap = tableListFromString(jsonStr);
              log.debug(JsonUtils.writeJsonStr(resultMap));
          } catch (Exception e) {
              log.error("parse error", e);
          }
          return resultMap;
      }

      // 处理方案一: 同一路由下所有请求方式合并为一个表格
      private Map<String, Object> getResultFromString(List<Table> result, String jsonStr) throws IOException {
          // convert JSON string to Map
          Map<String, Object> map = JsonUtils.readValue(jsonStr, HashMap.class);

          //解析model
          Map<String, ModelAttr> definitinMap = parseDefinitions(map);

          //解析paths
          Map<String, Map<String, Object>> paths = (Map<String, Map<String, Object>>) map.get("paths");
          if (paths != null) {
              Iterator<Entry<String, Map<String, Object>>> it = paths.entrySet().iterator();
              while (it.hasNext()) {
                  Entry<String, Map<String, Object>> path = it.next();

                  Iterator<Entry<String, Object>> it2 = path.getValue().entrySet().iterator();
                  // 1.请求路径
                  String url = path.getKey();

                  // 2. 循环解析每个子节点,适应同一个路径几种请求方式的场景
                  while (it2.hasNext()) {
                      Entry<String, Object> request = it2.next();

                      // 2. 请求方式,类似为 get,post,delete,put 这样
                      String requestType = request.getKey();

                      Map<String, Object> content = (Map<String, Object>) request.getValue();

                      // 4. 大标题(类说明)
                      String title = String.valueOf(((List) content.get("tags")).get(0));

                      // 5.小标题 (方法说明)
                      String tag = String.valueOf(content.get("summary"));

                      // 6.接口描述
                      String description = String.valueOf(content.get("summary"));

                      // 7.请求参数格式,类似于 multipart/form-data
                      String requestForm = "";
                      List<String> consumes = (List) content.get("consumes");
                      if (consumes != null && consumes.size() > 0) {
                          requestForm = StringUtils.join(consumes, ",");
                      }

                      // 8.返回参数格式,类似于 application/json
                      String responseForm = "";
                      List<String> produces = (List) content.get("produces");
                      if (produces != null && produces.size() > 0) {
                          responseForm = StringUtils.join(produces, ",");
                      }

                      // 9. 请求体
                      List<LinkedHashMap> parameters = (ArrayList) content.get("parameters");

                      // 10.返回体
                      Map<String, Object> responses = (LinkedHashMap) content.get("responses");

                      //封装Table
                      Table table = new Table();

                      table.setTitle(title);
                      table.setUrl(url);
                      table.setTag(tag);
                      table.setDescription(description);
                      table.setRequestForm(requestForm);
                      table.setResponseForm(responseForm);
                      table.setRequestType(requestType);
                      table.setRequestList(processRequestList(parameters, definitinMap));
                      table.setResponseList(processResponseCodeList(responses));

                      // 取出来状态是200时的返回值
                      Map<String, Object> obj = (Map<String, Object>) responses.get("200");
                      if (obj != null && obj.get("schema") != null) {
                          table.setModelAttr(processResponseModelAttrs(obj, definitinMap));
                      }

                      //示例
                      table.setRequestParam(processRequestParam(table.getRequestList()));
                      table.setResponseParam(processResponseParam(obj, definitinMap));

                      result.add(table);
                  }
              }
          }
          return map;
      }



      /**
       * 处理请求参数列表
       *
       * @param parameters
       * @param definitinMap
       * @return
       */
      private List<Request> processRequestList(List<LinkedHashMap> parameters, Map<String, ModelAttr> definitinMap) {
          List<Request> requestList = new ArrayList<>();
          if (!CollectionUtils.isEmpty(parameters)) {
              for (Map<String, Object> param : parameters) {
                  Object in = param.get("in");
                  Request request = new Request();
                  request.setName(String.valueOf(param.get("name")));
                  request.setType(param.get("type") == null ? "object" : param.get("type").toString());
                  if (param.get("format") != null) {
                      request.setType(request.getType() + "(" + param.get("format") + ")");
                  }
                  request.setParamType(String.valueOf(in));
                  // 考虑对象参数类型
                  if (in != null && "body".equals(in)) {
                      Map<String, Object> schema = (Map) param.get("schema");
                      Object ref = schema.get("$ref");
                      // 数组情况另外处理
                      if (schema.get("type") != null && "array".equals(schema.get("type"))) {
                          ref = ((Map) schema.get("items")).get("$ref");
                          request.setType("array");
                      }
                      if (ref != null) {
                          request.setType(request.getType() + ":" + ref.toString().replaceAll("#/definitions/", ""));
                          request.setModelAttr(definitinMap.get(ref));
                      }
                  }
                  // 是否必填
                  request.setRequire(false);
                  if (param.get("required") != null) {
                      request.setRequire((Boolean) param.get("required"));
                  }
                  // 参数说明
                  request.setRemark(String.valueOf(param.get("description")));
                  requestList.add(request);
              }
          }
          return requestList;
      }


      /**
      * 处理返回码列表
       *
       * @param responses 全部状态码返回对象
       * @return
       */
      private List<Response> processResponseCodeList(Map<String, Object> responses) {
          List<Response> responseList = new ArrayList<>();
          Iterator<Entry<String, Object>> resIt = responses.entrySet().iterator();
          while (resIt.hasNext()) {
              Entry<String, Object> entry = resIt.next();
              Response response = new Response();
              // 状态码 200 201 401 403 404 这样
              response.setName(entry.getKey());
              LinkedHashMap<String, Object> statusCodeInfo = (LinkedHashMap) entry.getValue();
              response.setDescription(String.valueOf(statusCodeInfo.get("description")));
              Object schema = statusCodeInfo.get("schema");
              if (schema != null) {
                  Object originalRef = ((LinkedHashMap) schema).get("originalRef");
                  response.setRemark(originalRef == null ? "" : originalRef.toString());
              }
              responseList.add(response);
          }
          return responseList;
      }

      /**
      * 处理返回属性列表
       *
       * @param responseObj
       * @param definitinMap
       * @return
       */
      private ModelAttr processResponseModelAttrs(Map<String, Object> responseObj, Map<String, ModelAttr> definitinMap) {
          Map<String, Object> schema = (Map<String, Object>) responseObj.get("schema");
          String type = (String) schema.get("type");
          String ref = null;
          //数组
          if ("array".equals(type)) {
              Map<String, Object> items = (Map<String, Object>) schema.get("items");
              if (items != null && items.get("$ref") != null) {
                  ref = (String) items.get("$ref");
              }
          }
          //对象
          if (schema.get("$ref") != null) {
              ref = (String) schema.get("$ref");
          }

          //其他类型
          ModelAttr modelAttr = new ModelAttr();
          modelAttr.setType(StringUtils.defaultIfBlank(type, StringUtils.EMPTY));
  
          if (StringUtils.isNotBlank(ref) && definitinMap.get(ref) != null) {
              modelAttr = definitinMap.get(ref);
          }
          return modelAttr;
      }

      /**
       * 解析Definition
       *
       * @param map
       * @return
       */
      private Map<String, ModelAttr> parseDefinitions(Map<String, Object> map) {
          Map<String, Map<String, Object>> definitions = (Map<String, Map<String, Object>>) map.get("definitions");
          Map<String, ModelAttr> definitinMap = new HashMap<>(256);
          if (definitions != null) {
              Iterator<String> modelNameIt = definitions.keySet().iterator();
              while (modelNameIt.hasNext()) {
                  String modeName = modelNameIt.next();
                  getAndPutModelAttr(definitions, definitinMap, modeName);
              }
          }
          return definitinMap;
      }

      /**
       * 递归生成ModelAttr
       * 对$ref类型设置具体属性
       */
      private ModelAttr getAndPutModelAttr(Map<String, Map<String, Object>> swaggerMap, Map<String, ModelAttr> resMap, String modeName) {
          ModelAttr modeAttr;
          if ((modeAttr = resMap.get("#/definitions/" + modeName)) == null) {
              modeAttr = new ModelAttr();
              resMap.put("#/definitions/" + modeName, modeAttr);
          } else if (modeAttr.isCompleted()) {
              return resMap.get("#/definitions/" + modeName);
          }
          Map<String, Object> modeProperties = (Map<String, Object>) swaggerMap.get(modeName).get("properties");
          if (modeProperties == null) {
              return null;
          }
          Iterator<Entry<String, Object>> mIt = modeProperties.entrySet().iterator();

          List<ModelAttr> attrList = new ArrayList<>();
          //解析属性
          while (mIt.hasNext()) {
              Entry<String, Object> mEntry = mIt.next();
              Map<String, Object> attrInfoMap = (Map<String, Object>) mEntry.getValue();
              ModelAttr child = new ModelAttr();
              child.setName(mEntry.getKey());
              child.setType((String) attrInfoMap.get("type"));
              if (attrInfoMap.get("format") != null) {
                  child.setType(child.getType() + "(" + attrInfoMap.get("format") + ")");
              }
              child.setType(StringUtils.defaultIfBlank(child.getType(), "object"));

              Object ref = attrInfoMap.get("$ref");
              Object items = attrInfoMap.get("items");
              if (ref != null || (items != null && (ref = ((Map) items).get("$ref")) != null)) {
                  String refName = ref.toString();
                  //截取 #/definitions/ 后面的
                  String clsName = refName.substring(14);
                  modeAttr.setCompleted(true);
                  ModelAttr refModel = getAndPutModelAttr(swaggerMap, resMap, clsName);
                  if (refModel != null) {
                      child.setProperties(refModel.getProperties());
                  }
                  child.setType(child.getType() + ":" + clsName);
              }
              child.setDescription((String) attrInfoMap.get("description"));
              attrList.add(child);
         }
          Object title = swaggerMap.get(modeName).get("title");
          Object description = swaggerMap.get(modeName).get("description");
          modeAttr.setClassName(title == null ? "" : title.toString());
          modeAttr.setDescription(description == null ? "" : description.toString());
          modeAttr.setProperties(attrList);
          return modeAttr;
      }

      /**
       * 处理返回值
       *
       * @param responseObj
       * @return
       */
      private String processResponseParam(Map<String, Object> responseObj, Map<String, ModelAttr> definitinMap) throws JsonProcessingException {
          if (responseObj != null && responseObj.get("schema") != null) {
              Map<String, Object> schema = (Map<String, Object>) responseObj.get("schema");
              String type = (String) schema.get("type");
              String ref = null;
              // 数组
              if ("array".equals(type)) {
                  Map<String, Object> items = (Map<String, Object>) schema.get("items");
                  if (items != null && items.get("$ref") != null) {
                      ref = (String) items.get("$ref");
                  }
              }
              // 对象
              if (schema.get("$ref") != null) {
                  ref = (String) schema.get("$ref");
              }
              if (StringUtils.isNotEmpty(ref)) {
                  ModelAttr modelAttr = definitinMap.get(ref);
                  if (modelAttr != null && !CollectionUtils.isEmpty(modelAttr.getProperties())) {
                      Map<String, Object> responseMap = new HashMap<>(8);
                      for (ModelAttr subModelAttr : modelAttr.getProperties()) {
                          responseMap.put(subModelAttr.getName(), getValue(subModelAttr.getType(), subModelAttr));
                      }
                      return JsonUtils.writeJsonStr(responseMap);
                  }
              }
          }
          return StringUtils.EMPTY;
      }

      /**
       * 封装请求体
       *
       * @param list
       * @return
       */
      private String processRequestParam(List<Request> list) throws IOException {
          Map<String, Object> headerMap = new LinkedHashMap<>();
          Map<String, Object> queryMap = new LinkedHashMap<>();
          Map<String, Object> jsonMap = new LinkedHashMap<>();
          if (list != null && list.size() > 0) {
              for (Request request : list) {
                  String name = request.getName();
                  String paramType = request.getParamType();
                  Object value = getValue(request.getType(), request.getModelAttr());
                  switch (paramType) {
                      case "header":
                          headerMap.put(name, value);
                          break;
                      case "query":
                          queryMap.put(name, value);
                          break;
                      case "body":
                          //TODO 根据content-type序列化成不同格式,目前只用了json
                          jsonMap.put(name, value);
                          break;
                      default:
                          break;

                  }
              }
          }
          String res = "";
          if (!queryMap.isEmpty()) {
              res += getUrlParamsByMap(queryMap);
          }
          if (!headerMap.isEmpty()) {
              res += " " + getHeaderByMap(headerMap);
          }
          if (!jsonMap.isEmpty()) {
              if (jsonMap.size() == 1) {
                  for (Entry<String, Object> entry : jsonMap.entrySet()) {
                      res += " -d '" + JsonUtils.writeJsonStr(entry.getValue()) + "'";
                  }
              } else {
                  res += " -d '" + JsonUtils.writeJsonStr(jsonMap) + "'";
              }
          }
          return res;
      }

      /**
       * 例子中,字段的默认值
       *
       * @param type      类型
       * @param modelAttr 引用的类型
       * @return
       */
      private Object getValue(String type, ModelAttr modelAttr) {
          int pos;
          if ((pos = type.indexOf(":")) != -1) {
              type = type.substring(0, pos);
          }
          switch (type) {
              case "string":
                  return "string";
              case "string(date-time)":
                  return "2020/01/01 00:00:00";
              case "integer":
              case "integer(int64)":
              case "integer(int32)":
                  return 0;
              case "number":
                  return 0.0;
              case "boolean":
                  return true;
              case "file":
                  return "(binary)";
              case "array":
                  List list = new ArrayList();
                  Map<String, Object> map = new LinkedHashMap<>();
                  if (modelAttr != null && !CollectionUtils.isEmpty(modelAttr.getProperties())) {
                      for (ModelAttr subModelAttr : modelAttr.getProperties()) {
                          map.put(subModelAttr.getName(), getValue(subModelAttr.getType(), subModelAttr));
                      }
                  }
                  list.add(map);
                  return list;
              case "object":
                  map = new LinkedHashMap<>();
                  if (modelAttr != null && !CollectionUtils.isEmpty(modelAttr.getProperties())) {
                      for (ModelAttr subModelAttr : modelAttr.getProperties()) {
                          map.put(subModelAttr.getName(), getValue(subModelAttr.getType(), subModelAttr));
                      }
                  }
                  return map;
              default:
                  return null;
          }
      }

      /**
       * 将map转换成url
       */
      public static String getUrlParamsByMap(Map<String, Object> map) {
          if (map == null || map.isEmpty()) {
              return "";
          }
          StringBuffer sb = new StringBuffer();
          for (Entry<String, Object> entry : map.entrySet()) {
              sb.append(entry.getKey() + "=" + entry.getValue());
              sb.append("&");
          }
          String s = sb.toString();
          if (s.endsWith("&")) {
              s = StringUtils.substringBeforeLast(s, "&");
          }
          return s;
      }

      /**
       * 将map转换成header
       */
      public static String getHeaderByMap(Map<String, Object> map) {
          if (map == null || map.isEmpty()) {
              return "";
          }
          StringBuffer sb = new StringBuffer();
          for (Entry<String, Object> entry : map.entrySet()) {
              sb.append("--header '");
              sb.append(entry.getKey() + ":" + entry.getValue());
              sb.append("'");
          }
          return sb.toString();
      }
  }

添加CoverUtils文件

  @Service
  public class CoverUtil {

      /**
       * bean 转换为string
       * @param value
       * @param <T>
       * @return
       */
      public static <T> String beanToString(T value){
          if (value == null)
              return null;
          Class<?> clazz = value.getClass();//value的类型
          if (clazz == int.class ||clazz==Integer.class){
              return ""+value;
          }
          else if (clazz == String.class){
              return (String)value;
          }
          else if (clazz == long.class||clazz==Long.class){
             return ""+value;
          }else {
              return JSON.toJSONString(value);//由对象转化为json字符串
          }
      }
    /**
       * string-->bean
       * @param str
       * @param clazz
       * @param <T>
       * @return
       */
      public static <T> T stringToBean(String str, Class<T> clazz){
          if (str == null  || str.length()<=0 || clazz == null)
              return null;
          if (clazz == int.class || clazz == Integer.class){
              return (T) Integer.valueOf(str);
          }
          else if (clazz == Long.class || clazz==long.class){
              return (T)Long.valueOf(str);
          }
          else if (clazz == String.class){
              return (T)str;
          }
          else
              return JSON.toJavaObject(JSON.parseObject(str),clazz);
      }

      public static Trade stringToTrade(String str){
          Trade trade = new Trade();
          Map maps = (Map)JSON.parse(str);
          if(maps.containsKey("orderNo")){
              trade.setOrderno(maps.get("orderNo").toString());
          }
          if(maps.containsKey("storeCode")){
              trade.setStorecode(Integer.valueOf(maps.get("storeCode").toString()));
          }
          if(maps.containsKey("userId")){
              trade.setUserid(maps.get("userId").toString());
          }
          if(maps.containsKey("orderFlag")){
              trade.setOrderflag(Integer.valueOf(maps.get("orderFlag").toString()));
          }
          if(maps.containsKey("source")){
              trade.setSource(Integer.valueOf(maps.get("source").toString()));
          }
          if(maps.containsKey("orderAmount")){
              trade.setOrderamount(Long.valueOf(maps.get("orderAmount").toString()));
          }
          if(maps.containsKey("realPayAmount")){
              trade.setRealpayamount(Long.valueOf(maps.get("realPayAmount").toString()));
          }
          if(maps.containsKey("saleDetailList")){
              trade.setSaledetaillist(maps.get("saleDetailList").toString());
          }
          if(maps.containsKey("salePayList")){
              trade.setSalepaylist(maps.get("salePayList").toString());
          }
          if(maps.containsKey("point")){
              trade.setPoint(Long.valueOf(maps.get("point").toString()));
          }
          if(maps.containsKey("gradePoint")){
              trade.setGradepoint(Long.valueOf(maps.get("gradePoint").toString()));
          }
          if(maps.containsKey("posCode")){
              trade.setPoscode(maps.get("posCode").toString());
          }
          if(maps.containsKey("memo")){
              trade.setMemo(maps.get("memo").toString());
          }
          if(maps.containsKey("createDate")){
              trade.setCreatedate(Long.valueOf(maps.get("createDate").toString()));
          }
          if(maps.containsKey("finishDate")){
              trade.setFinishdate(Long.valueOf(maps.get("finishDate").toString()));
          }
          if(maps.containsKey("type")){
              trade.setType(Integer.valueOf(maps.get("type").toString()));
          }
          if(maps.containsKey("payCode")){
              trade.setPaycode(maps.get("payCode").toString());
          }
          if(maps.containsKey("createTime")){
              trade.setCreatetime(Long.valueOf(maps.get("createTime").toString()));
          }

         return trade;
      }
  }

添加JsonUtils文件

  public class JsonUtils {

      private static ObjectMapper objectMapper = new ObjectMapper();

      static {
          objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
          objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
          objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
          objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
          objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
      }

      public static <T> T readValue(String jsonStr, Class<T> clazz) throws IOException {
          return objectMapper.readValue(jsonStr, clazz);
      }

      public static <T> List<T> readListValue(String jsonStr, Class<T> clazz) throws IOException {
          JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, clazz);
          return objectMapper.readValue(jsonStr, javaType);
      }

      public static ArrayNode readArray(String jsonStr) throws IOException {
          JsonNode node = objectMapper.readTree(jsonStr);
          if (node.isArray()) {
              return (ArrayNode) node;
          }
          return null;
      }

      public static JsonNode readNode(String jsonStr) throws IOException {
          return objectMapper.readTree(jsonStr);
      }

      public static String writeJsonStr(Object obj) throws JsonProcessingException {
          return objectMapper.writeValueAsString(obj);
      }

      public static ObjectNode createObjectNode() {
          return objectMapper.createObjectNode();
      }

      public static ArrayNode createArrayNode() {
          return objectMapper.createArrayNode();
      }

  }

添加MenuUtils文件

  public class MenuUtils {

      public static Integer count = 0;
      public static String menuStr = "null";

      public static boolean isMenu(String tags) {
          if (menuStr.equals(tags)) {
              count++;
          } else {
              menuStr = tags;
              count = 0;
          }
          if (count == 0) {
             return true;
          } else {
              return false;
          }
      }
  }

在resources目录下添加template文件,里面包含html文件

  <!DOCTYPE html>
  <html xmlns:th="http://www.thymeleaf.org">
  <head>
      <meta http-equiv="Content-Type" content="application/msword; charset=utf-8"/>
      <title>toWord</title>
          <style type="text/css">
          .bg {
              font-size: 14.5px;
              font-weight: bold;
              color: #000;
              background-color: #559e68;
          }

          table {
              border-width: 1px;
              border-style: solid;
              border-color: black;
             table-layout: fixed;
          }

          tr {
              height: 32px;
              font-size: 12px;
          }

          td {
              padding-left: 10px;
              border-width: 1px;
              border-style: solid;
              border-color: black;
              height: 32px;
              overflow: hidden;
              word-break: break-all;
              word-wrap: break-word;
              font-size: 14.5px;
          }

         .bg td {
             font-size: 14.5px;
          }

          tr td {
              font-size: 14.5px;
          }

          .specialHeight {
              height: 40px;
          }

          .first_title {
              height: 60px;
              line-height: 60px;
             margin: 0;
              font-weight: bold;
              font-size: 21px;
          }

          .second_title {
              height: 40px;
              line-height: 40px;
              margin: 0;
              font-size: 18.5px;
          }

          .doc_title {
              font-size: 42.5px;
             text-align: center;
          }

          .download_btn {
              float: right;
          }

          body {
              font-family: 思源黑体 Normal;
          }
      </style>
  </head>

  <body>
  <div style="width:1000px; margin: 0 auto">
      <div>
          <p class="doc_title" th:text="${info.title +'('+ info.version +')'}"></p>
          <a class="download_btn" th:if="${download == 1}" th:href="${'/downloadWord?url='+ url}">下载文档</a>
          <br>
      </div>
      <div th:each="tableMap:${tableMap}" style="margin-bottom:20px;">
          <!--这个是类的说明-->
          <h4 class="first_title" th:text="${tableMap.key}"></h4>
          <div th:each="table,tableStat:${tableMap.value}">

              <!--这个是每个请求的说明,方便生成文档后进行整理-->
              <h5 class="second_title" th:text="${tableStat.count} + ')' + ${table.tag}"></h5>

              <table border="1" cellspacing="0" cellpadding="0" width="100%">
                  <tr class="bg">
                      <td colspan="5" th:text="${table.tag}"></td>
                  </tr>
                  <tr>
                      <td width="25%">接口描述</td>
                      <td colspan="4" th:text="${table.description}"></td>
                  </tr>
                  <tr>
                      <td>URL</td>
                      <td colspan="4" th:text="${table.url}"></td>
                  </tr>
                  <tr>
                      <td>请求方式</td>
                      <td colspan="4" th:text="${table.requestType}"></td>
                  </tr>
                  <tr>
                      <td>请求类型</td>
                      <td colspan="4" th:text="${table.requestForm}"></td>
                  </tr>
                  <tr>
                      <td>返回类型</td>
                      <td colspan="4" th:text="${table.responseForm}"></td>
                  </tr>

                  <tr class="bg">
                      <td>参数名</td>
                      <td width="15%">数据类型</td>
                      <td width="15%">参数类型</td>
                      <td width="15%">是否必填</td>
                      <td width="29%">说明</td>
                  </tr>

                  <th:block th:each="request, c:${table.requestList}">
                      <tr>
                          <td align="left" th:text="${c.count} + '.' + ${request.name}"></td>
                          <td th:text="${request.type}"></td>
                          <td th:text="${request.paramType}"></td>
                          <td th:if="${request.require}" th:text="Y"></td>
                          <td th:if="${!request.require}" th:text="N"></td>
                          <td th:text="${request.remark}"></td>
                          <!--                        <td th:if="${request.modelAttr}" th:text="asdfagadfg"></td>-->
                      </tr>
                      <th:block th:if="${request.modelAttr}">
                          <tbody th:include="this::request(${request.modelAttr.properties},${c.count} + '.', 1)"/>
                      </th:block>


                  </th:block>

                  <tr class="bg">
                      <td>状态码</td>
                      <td colspan="2">描述</td>
                      <td colspan="2">说明</td>
                  </tr>

                  <tr th:each="response:${table.responseList}">
                      <td th:text="${response.name}"></td>
                      <td colspan="2" th:text="${response.description}"></td>
                      <td colspan="2" th:text="${response.remark}"></td>
                  </tr>

                  <tr class="bg">
                      <td>返回属性名</td>
                      <td colspan="2">类型</td>
                      <td colspan="2">说明</td>
                  </tr>

  <!--               对返回参数 递归生成行-->
                  <tbody th:include="this::response(${table.modelAttr.properties},'', 1)"/>

                  <tr class="bg">
                      <td colspan="5">示例</td>
                  </tr>
                  <tr class="specialHeight">
                      <td class="bg">请求参数</td>
                      <td colspan="4" th:text="${table.requestParam}"></td>
                  </tr>
                  <tr class="specialHeight">
                      <td class="bg">返回值</td>
                      <td colspan="4" th:text="${table.responseParam}"></td>
                  </tr>

              </table>
          </div>
      </div>
  </div>

  <th:block th:fragment="request(properties,count, lv)">
      <th:block th:each="p,c : ${properties}">
          <tr>
              <td align="left" th:text="${count} + '' + ${c.count} + '.' + ${p.name}"
                  th:style="|padding-left:${10*lv}px|"></td>
              <td th:text="${p.type}"></td>
              <td></td>
              <td th:if="${p.require}" th:text="Y"></td>
              <td th:if="${!p.require}" th:text="N"></td>
              <td th:text="${p.description}"></td>
          </tr>
          <th:block th:unless="${#lists.isEmpty(p.properties)}"
                    th:include="this::request(${p.properties},${count} + '' + ${c.count} + '.',${lv+1})"/>
     </th:block>
  </th:block>

  <th:block th:fragment="response(properties,count, lv)">
      <th:block th:each="p,c : ${properties}">
          <tr>
              <td align="left" th:text="${count} + '' + ${c.count} + '.' + ${p.name}"
                  th:style="|padding-left:${10*lv}px|"></td>
              <td colspan="2" th:text="${p.type}"></td>
              <td colspan="2" th:text="${p.description}"></td>
          </tr>
          <th:block th:unless="${#lists.isEmpty(p.properties)}"
                    th:include="this::response(${p.properties},${count} + '' + ${c.count} + '.',${lv+1})"/>
      </th:block>
  </th:block>
  </body>
  </html>

输入swagger的地址发送请求下载word

posted @ 2020-12-03 17:27  怀念ぅ风锍  阅读(212)  评论(0)    收藏  举报