NutzCN Logo
问答 使用nutz做rest接口开发,怎样与swagger-ui集成?
发布于 3082天前 作者 qq_f114016f 2678 次浏览 复制 上一个帖子 下一个帖子
标签:

如题

4 回复

核心是不是如何生成"swagger.json"这个文件的问题?

看了一下swagger与spring的集成 http://blog.csdn.net/fengspg/article/details/43705537

看来swagger是一套注解规范?? 它自带mvc解析,但可以不用???

稍微试了一下

web.xml添加

	<servlet>
		<servlet-name>swagger</servlet-name>
		<servlet-class>net.wendal.nutzbook.mvc.SwaggerBootstrap</servlet-class>
		<load-on-startup>2</load-on-startup>
		<init-param>
			<param-name>swagger.resource.package</param-name>
			<param-value>net.wendal.nutzbook</param-value>
		</init-param>
		<init-param>
			<param-name>swagger.pretty.print</param-name>
			<param-value>true</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>swagger</servlet-name>
		<url-pattern>/api2/swagger.json</url-pattern>
	</servlet-mapping>

SwaggerBootstrap类

package net.wendal.nutzbook.mvc;

import java.io.IOException;
import java.util.Set;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;

import io.swagger.config.Scanner;
import io.swagger.config.SwaggerConfig;
import io.swagger.models.Swagger;
import io.swagger.servlet.Reader;
import io.swagger.servlet.config.ServletScanner;
import io.swagger.servlet.config.WebXMLReader;
import io.swagger.util.Json;

@SuppressWarnings("serial")
public class SwaggerBootstrap extends HttpServlet {
    
    protected Swagger swagger;

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        super.init(servletConfig);
        
        SwaggerConfig reader = new WebXMLReader(servletConfig);
        Scanner scanner = new ServletScanner(servletConfig);
        
        swagger = new Swagger();
        reader.configure(swagger);
        final Set<Class<?>> classes = scanner.classes();
        if (classes != null) {
            Reader.read(swagger, classes);
        }
    }
    
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws JsonProcessingException, IOException{
        ((HttpServletResponse)resp).getWriter().println(Json.mapper().writeValueAsString(swagger));
    }
}

然后找个入口方法标注好@Api等注解后, 启动后访问 /api2/swagger.json

{"swagger":"2.0","info":{"version":"Swagger Server"},"schemes":["http"],"paths":{"/yvr/api/v1/topics":{"get":{"summary":"????????","operationId":"topics","parameters":[],"responses":{"200":{"description":"successful operation","schema":{"type":"object"}}}}}}}

好的 ,我试试,谢谢了

添加回复
请先登陆
回到顶部