Recently, due to the need of the project, we need to integrate the swagger-ui product for automatic generation of api documents. We have studied it for a long time. Of course, we have trampled a lot of pits. It is a summary of some experience. I hope it can help the students who need it to take less detours. I guess I haven't learnt Chinese well. Some expressions may not be ideal, so you can click on them. [Full Portal] Look directly at the source code! Well, no more nonsense, go straight to dry goods, start to work!
[Part 1]: Building Spring mvc+mybatis application
You have to build a web application, and it can run, that is, you can get data from the database back to the page, or you can submit data from the page to the database! Such a simple architecture should be no problem.
Connect database configuration file (non-web layer) - spring-mybatis.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mybatis="http://mybatis.org/schema/mybatis-spring" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- Injection automatic scanning non- web layer --> <context:component-scan base-package="org.com.swagger.code"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <context:property-placeholder location="classpath:config/jdbc.properties"/> <!-- Database connection pool --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!-- Configuration filtering --> <property name="filters" value="stat"/> <!-- Configuration initialization size, minimum, maximum --> <property name="initialSize" value="10"/> <property name="minIdle" value="10"/> <property name="maxActive" value="100"/> <!-- Configuration to get the connection waiting timeout time --> <property name="maxWait" value="60000"/> <!-- How often is the configuration interval detected to detect idle connections that need to be closed in milliseconds? --> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <!-- Configure the minimum lifetime of a connection in the pool in milliseconds --> <property name="minEvictableIdleTimeMillis" value="300000"/> <!-- Check if the connection is valid SQL --> <property name="validationQuery" value="SELECT 'x'"/> <property name="testWhileIdle" value="true"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> </bean> <!-- scanning mapper Mapping file --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="mapperLocations" value="classpath:mapper/*.xml"></property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="org.com.swagger.code.dao"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
web Layer Profile-spring-mvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"> <!-- Automatic scanning web Layer bean --> <context:component-scan base-package="org.com.swagger.code" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- Open notes --> <context:annotation-config/> <!-- Configuration view --> <!-- <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> <property name="exposeRequestAttributes" value="true" /> <property name="exposeSessionAttributes" value="true" /> <property name="viewClass"> <value>org.springframework.web.servlet.view.freemarker.FreeMarkerView</value> </property> <property name="cache"><value>true</value></property> <property name="prefix"><value>/WEB-INF/views/</value></property> <property name="suffix"><value>.ftl</value></property> <property name="contentType"> <value>text/html; charset=UTF-8</value> </property> </bean> --> <mvc:annotation-driven /> <!-- swagger-ui To configure java class bean --> <bean id="swaggerConfig" class="org.com.swagger.code.swagger.SwaggerConfig"/> <!-- Automatically registered SimpleUrlHandlerMapping Access to resources --> <!-- servlet When looking for pages, go dispatcherServlet Route. When you can't find it, you will report 404 plus this default servlet Time, servlet When you can't find it, you look for static content. --> <mvc:default-servlet-handler/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> <property name="contentType" value="text/html;charset=UTF-8"></property> </bean> <!--avoid IE implement AJAX Return when JSON Download file appears --> <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> </list> </property> </bean> <!-- start-up SpringMVC Annotation function to complete requests and annotations POJO Mapping --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="fastJsonHttpMessageConverter" /> <!-- JSON Converter --> </list> </property> </bean> <!-- Configuration file upload, if not using file upload can not be configured, of course, if not, then the configuration file does not need to introduce the upload component package. --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- Default encoding --> <property name="defaultEncoding" value="UTF-8" /> <!-- Maximum file size --> <property name="maxUploadSize" value="10485760000" /> <!-- Maximum in memory --> <property name="maxInMemorySize" value="40960" /> </bean> <!-- FreeMarker Get the context path in --> <!-- <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="/WEB-INF/views/"/> <property name="freemarkerSettings"> <props> <prop key="template_update_delay">3</prop> <prop key="defaultEncoding">UTF-8</prop> <prop key="url_escaping_charset">UTF-8</prop> <prop key="locale">zh_CN</prop> <prop key="boolean_format">true,false</prop> <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop> <prop key="date_format">yyyy-MM-dd</prop> <prop key="time_format">HH:mm:ss</prop> <prop key="number_format">0.######</prop> <prop key="whitespace_stripping">true</prop> <prop key="classic_compatible">true</prop> </props> </property> <property name="freemarkerVariables"> <map> <entry key="webRoot" value="/vrum/"></entry> </map> </property> </bean>--> </beans>
servlet configuration file - web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/spring-mybatis.xml</param-value> </context-param> <!-- Design Path Variable Value --> <context-param> <param-name>webAppRootKey</param-name> <param-value>springmvc.root</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/</url-pattern> </filter-mapping> <!-- Log record --> <context-param> <!-- Log Profile Path --> <param-name>log4jConfigLocation</param-name> <param-value>classpath:config/log4j.properties</param-value> </context-param> <context-param> <!-- Refresh intervals for log pages --> <param-name>log4jRefreshInterval</param-name> <param-value>6000</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!-- spring mvc --> <servlet> <servlet-name>spring-mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/spring-mvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring-mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.jpg</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.png</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.gif</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.ico</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.xls</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.doc</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.json</url-pattern> </servlet-mapping> <!-- Font Relevance Start --> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.eot</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.svg</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.ttf</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.woff</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.woff2</url-pattern> </servlet-mapping> <!-- End of font correlation --> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
Well, the above configuration can already build a simple web application, oh! By the way, there are dependency packages
maven-pom dependency file-pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>swagger.code</groupId> <artifactId>swagger-code</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>swagger-code Maven Webapp</name> <url>http://mvnrepository.com/</url> <!-- version control --> <properties> <asm.version>3.3.1</asm.version> <javax.inject.version>1</javax.inject.version> <spring.version>4.0.9.RELEASE</spring.version> <jedis.version>2.7.3</jedis.version> <mybatis.version>3.2.8</mybatis.version> <mybatis-spring.version>1.2.2</mybatis-spring.version> <mysql.version>5.1.26</mysql.version> <druid.version>1.0.9</druid.version> <log4j.version>1.2.17</log4j.version> <slf4j.version>1.7.5</slf4j.version> <poi.version>3.10-FINAL</poi.version> <druid.version>1.0.15</druid.version> <javax.annotation-api.version>1.2</javax.annotation-api.version> <mail.version>1.4.7</mail.version> <ezmorph.version>1.0.6</ezmorph.version> <gson.version>2.8.0</gson.version> <icu4j.version>3.4.4</icu4j.version> <jpush-client.version>3.1.3</jpush-client.version> <lombok.version>1.16.6</lombok.version> <echarts.version>3.0.0</echarts.version> <commons-net.version>3.4</commons-net.version> <commons-lang3.version>3.1</commons-lang3.version> <commons-io.version>2.4</commons-io.version> <commons-codec.version>1.8</commons-codec.version> <commons-fileupload.version>1.3.2</commons-fileupload.version> <commons-beanutils.version>1.8.3</commons-beanutils.version> <jackson-asl.version>1.9.13</jackson-asl.version> <curator-framework.version>1.1.10</curator-framework.version> <commons-pool2.version>2.4.2</commons-pool2.version> <pjl-comp-filter.version>1.7</pjl-comp-filter.version> <aspectjweaver.version>1.8.9</aspectjweaver.version> <json-lib.version>2.4</json-lib.version> <flexjson.version>3.3</flexjson.version> <jaxen.version>1.1.1</jaxen.version> <jdom.version>1.1</jdom.version> <im4java.version>1.4.0</im4java.version> <jsoup.version>1.8.3</jsoup.version> <javax.servlet-api.version>3.1.0</javax.servlet-api.version> <javax.servlet.jsp-api.version>2.3.1</javax.servlet.jsp-api.version> <bcprov-jdk15on.version>1.52</bcprov-jdk15on.version> <jedis.version>2.7.3</jedis.version> <ehcache-core.version>2.5.7</ehcache-core.version> <ehcache-web.version>2.0.4</ehcache-web.version> <spring-data-redis.vresion>1.5.2.RELEASE</spring-data-redis.vresion> </properties> <dependencies> <!-- spring Core dependence --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.9.5</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-core</artifactId> <version>1.3</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>${jedis.version}</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring.version}</version> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> </dependency> <!--json-lib --> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>${json-lib.version}</version> <classifier>jdk15</classifier> </dependency> <dependency> <groupId>net.sf.flexjson</groupId> <artifactId>flexjson</artifactId> <version>${flexjson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.7</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.8.5</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>${jackson-asl.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.7</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.28</version> </dependency> <!-- Freemaker --> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency> <!-- javax Provided annotation --> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>${javax.inject.version}</version> </dependency> <!-- junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- aop agent --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.9</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.6</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency> <dependency> <groupId>net.sourceforge.pjl-comp-filter</groupId> <artifactId>pjl-comp-filter</artifactId> <version>${pjl-comp-filter.version}</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version> </dependency> <dependency> <groupId>io.reactivex.rxjava2</groupId> <artifactId>rxjava</artifactId> <version>2.0.8</version> </dependency> <!-- log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.7</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.7</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.7.7</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-compress</artifactId> <version>1.9</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>${commons-lang3.version}</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>${commons-codec.version}</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>${commons-io.version}</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>${commons-pool2.version}</version> </dependency> <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>${commons-net.version}</version> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>${commons-beanutils.version}</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>jaxen</groupId> <artifactId>jaxen</artifactId> <version>${jaxen.version}</version> </dependency> <dependency> <groupId>org.jdom</groupId> <artifactId>jdom</artifactId> <version>${jdom.version}</version> </dependency> <dependency> <groupId>org.im4java</groupId> <artifactId>im4java</artifactId> <version>${im4java.version}</version> </dependency> <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>${jsoup.version}</version> </dependency> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> <version>${bcprov-jdk15on.version}</version> </dependency> <dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>${javax.annotation-api.version}</version> </dependency> <dependency> <groupId>net.sf.ezmorph</groupId> <artifactId>ezmorph</artifactId> <version>${ezmorph.version}</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>com.ibm.icu</groupId> <artifactId>icu4j</artifactId> <version>${icu4j.version}</version> </dependency> <!-- servlet api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${javax.servlet-api.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>${spring-data-redis.vresion}</version> </dependency> <dependency> <groupId>de.ruedigermoeller</groupId> <artifactId>fst</artifactId> <version>2.05</version> </dependency> <!-- swagger-ui Core package --> <dependency> <groupId>com.mangofactory</groupId> <artifactId>swagger-springmvc</artifactId> <version>0.9.5</version> </dependency> </dependencies> <build> <finalName>swagger-code</finalName> </build> </project>
Project Package Structure Diagram
Here I believe you can easily build a web application based on spring mvc + mybatis framework!
[Part 2]: Prepare a set of static files needed by swagger-ui
You must also have a set of static swagger-ui resources, such as: js, css, img, etc. The official website provides github's download address, but I have tried it and it is useless, so I use a 15-year version of the document, at least this set of documents I run to prove that it is available!
Let's start by showing the file structure of swagger-ui
Yes, you're right. There are so many files, or there will be a Bug: No operations defined in spec!
I believe you are familiar with this bug. This bug is caused by the default of ui static resources.
[Part 3]: Eastern Wind
Well, the above has already prepared all the necessary preparations, only owe the east wind can start a fire!
SwaggerConfig.java class, the only java class that needs to be written in the java background
package org.com.swagger.code.swagger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import com.mangofactory.swagger.configuration.SpringSwaggerConfig; import com.mangofactory.swagger.models.dto.ApiInfo; import com.mangofactory.swagger.plugin.EnableSwagger; import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin; @Configuration @EnableSwagger @EnableWebMvc public class SwaggerConfig { private SpringSwaggerConfig springSwaggerConfig; /** * Required to autowire SpringSwaggerConfig */ @Autowired public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) { this.springSwaggerConfig = springSwaggerConfig; } /** * Every SwaggerSpringMvcPlugin bean is picked up by the swagger-mvc * framework - allowing for multiple swagger groups i.e. same code base * multiple swagger resource listings. */ @Bean public SwaggerSpringMvcPlugin customImplementation() { // No filtering for the time being /** * includePatterns:In the past, interface functions could filter which interfaces were not displayed by regularization */ return new SwaggerSpringMvcPlugin(this.springSwaggerConfig).apiInfo(apiInfo()).includePatterns(".*?"); } private ApiInfo apiInfo() { ApiInfo apiInfo = new ApiInfo( "spring mvc Integrate swagger Documentation tools", "API Document Integration Tool", "swagger-code", "http://127.0.0.1:8080", "87182767@qq.com", "version 1.0.0" ); return apiInfo; } }
The above configuration class is written. What's the use of this class? My personal exploration found that this class is a configuration file of swagger-ui, through which swagger-ui can scan all web layers (i.e. controller s or actions) for data parsing, and then form documents in json format in a beautiful way in the swagger-ui interface! Note that the above annotations can not be saved!
[Part 4] It's time to take delivery.
It's time to check the correctness of the program. At this time, we can get a test class to test.
swagger-ui test controller
package org.com.swagger.code.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.com.swagger.code.constants.Constants; import org.com.swagger.code.constants.Result; import org.com.swagger.code.entity.User; import org.com.swagger.code.service.UserService; 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.alibaba.fastjson.JSON; import com.sun.istack.internal.logging.Logger; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.annotations.ApiParam; @Api(value="/store",description="Shop") @Controller @RequestMapping("user") public class UserController { private final Logger log = Logger.getLogger(UserController.class); @Autowired private UserService userService; @RequestMapping(value="/get-user",method=RequestMethod.POST,produces={"application/json;charset=utf-8"}) @ResponseBody public String getUser(HttpServletRequest req,HttpServletResponse res,@RequestParam int id){ Result<User> result = null; User user = userService.getUser(id); if(user != null){ result = new Result<User>(Constants.SUCCESS_CODE, Constants.SUCCESS_MSG, user); }else{ result = new Result<User>(Constants.ERROR_CODE, Constants.ERROR_MSG); } return JSON.toJSONString(result); } @ResponseBody @RequestMapping(value = "/view", method = RequestMethod.GET, produces = {"application/json; charset=utf-8","application/xml"}) @ApiOperation(value = "adopt ID query USER information", httpMethod = "GET", notes = "adopt ID query USER information") public String getUserById( @ApiParam(required = true, name = "id", value = "ID") @RequestParam(value = "id") int id,HttpServletRequest request) { log.info(String.format("at function, %s", id)); Result<User> result = null; User user = userService.getUser(id); if(user != null){ result = new Result<User>(Constants.SUCCESS_CODE, Constants.SUCCESS_MSG, user); }else{ result = new Result<User>(Constants.ERROR_CODE, Constants.ERROR_MSG); } return JSON.toJSONString(result); } }
Explain @ApiOperation and @ApiParam. There are two interfaces in this controller. One is getUser and the other is getUserById. In fact, the two interfaces return the same result. If there is one of the above two, let's compare the results.
[General Notes]
[Add @ApiOperation and @ApiParam buff s]
Explanation of doubtful points in [Part 4] uuuuuuuuuuu
I added one in the spring-mvc-servlet.xml file
<bean id="swaggerConfig" class="org.com.swagger.code.swagger.SwaggerConfig"/>
Such a bean object, this bean should be used to obtain the return data of the web application and display it in the static page. If you are interested, you can see the source code of swagger-spring MVC to understand. In summary, we can see that only two parts need to be handwritten (belonging to the additional part of spring MVC + mybatis): one is swaggerConfig class, and the other is swaggerConfig be. An object
To run swagger-ui, you need to do a little thing before running it.
- Modify this line of code in index.html in swagger-ui's static resources a little bit
- $(function () {
var url = window.location.search.match(/url=([^&]+)/);
if (url && url.length > 1) {
url = decodeURIComponent(url[1]);
} else {
//url = "http://petstore.swagger.io/v2/swagger.json";
url = "http://127.0.0.1:8080/swagger-code/api-docs "//domain name/project name/api-docs
} - Domain name = http://127.0.0.1:8080
- Project name = swagger-code
Okay, Sao Nien, you can sail, go and try how you feel, and then you don't have to worry about writing documents anymore!