Build "1, integrated swagger" based on the rest service framework under SPRINGMVC

Source: Internet
Author: User

Build "1, integrated swagger" based on the rest service framework under SPRINGMVC 1. Requirements background
SpringMVC本身就可以开发出基于rest风格的服务,通过简单的配置,即可快速开发出一个可供客户端调用的rest服务,通常这些服务要不就是用于手机app的开发,要不就是提供给第三方开发者使用,不管哪种情况,你都需要提供详细的说明给别人,而Swagger就是为这种情况而生的,通过在接口上的注解,生成可供第三方模拟测试和阅读的接口列表,既美观又使用,真是行走江湖之必备良药。【XmPlatform原创,转载的话请注明】下面先上美图:

好了,下面言归正传,该如何将Swagger集成到springMVC中呢?
2. Dependent packages and Swagger-ui versions
    • If you are using Maven, the dependency package is as follows:
    <groupId>com.mangofactory</groupId> <artifactId>swagger-springmvc</artifactId> <versi On>1.0.2</version></dependency><dependency> <groupid>com.mangofactory</groupid > <artifactId>swagger-models</artifactId> <version>1.0.2</version></dependency> <dependency> <groupId>com.wordnik</groupId> <artifactid>swagger-annotations</ artifactid> <version>1.3.11</version></dependency><!--swagger-springmvc Dependencies-- ><dependency> <groupId>com.google.guava</groupId> <artifactid>guava</artifactid > <version>15.0</version></dependency><dependency> <groupId> Com.fasterxml.jackson.core</groupid> <artifactId>jackson-annotations</artifactId> <version >2.4.4</version></dependency><dependency> &LT;GROUPID&GT;COM.FASTERXML.jackson.core</groupid> <artifactId>jackson-databind</artifactId> <version>2.4.4</ Version></dependency><dependency> <groupId>com.fasterxml.jackson.core</groupId> < Artifactid>jackson-core</artifactid> <version>2.4.4</version></dependency>< dependency> <groupId>com.fasterxml</groupId> <artifactId>classmate</artifactId> <ve Rsion>1.1.0</version></dependency>
    • If you are using the Jeesite framework, you can simply introduce the following three lib:
swagger-annotations-1.3.11.jarswagger-models-1.0.2.jarswagger-springmvc-1.0.2.jar
    • Swagger-ui version

You can download the latest version to Https://github.com/swagger-api/swagger-ui/releases, currently the latest version is 2.1.4

3. New configuration Java File

Create a new Java file named Swaggerconfig in your Javaweb project, with the following code:

Import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.context.annotation.Bean ; Import Org.springframework.context.annotation.componentscan;import Org.springframework.context.annotation.configuration;import Org.springframework.web.servlet.config.annotation.defaultservlethandlerconfigurer;import Org.springframework.web.servlet.config.annotation.enablewebmvc;import Org.springframework.web.servlet.config.annotation.webmvcconfigureradapter;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;/** * @author XIEGX * @version creation time: 2016-8-16 2:01:10 * Swaggerui configuration */@Configuration @enableswagger@enablewebmvc@componentscan (basepackages ={"Com.xxx.soa"}) public class    Swaggerconfig extends Webmvcconfigureradapter {private Springswaggerconfig springswaggerconfig; /** * RequireD to Autowire Springswaggerconfig */@Autowired public void Setspringswaggerconfig (Springswaggerconfig springswa    Ggerconfig) {this.springswaggerconfig = Springswaggerconfig; }/** * Every Swaggerspringmvcplugin bean is picked up by the SWAGGER-MVC * framework-allowing for multiple S     Wagger groups i.e. same Code base * Multiple Swagger resource listings. */@Bean public swaggerspringmvcplugin customimplementation () {return new Swaggerspringmvcplugin (THIS.SPR Ingswaggerconfig). Apiinfo (Apiinfo ()). IncludePatterns (". *"). Swaggergroup ("X    Mplatform "). Apiversion (" 1.0.0 "); } @Override public void configuredefaultservlethandling (Defaultservlethandlerconfigurer configurer) {confi      Gurer.enable (); }/* * "title title", * "description description", * "Termsofserviceurl", * "Contact email", * "type of license License", * " Link to license License URL "*/private Apiinfo Apiinfo () {apiinfo apiinfo = new Apiinfo ("XXX Platform API Documentation", "Background restful API",        "",//"[email protected]", "", "" ");    return apiinfo; }}

Note: Basepackages is the path of the scanned package (the path of the package where your controller is located), the other things we should see should be understood, not much to say.

4. New test controller

For example, create a new Testcontroller.java with the following code:

@Controller@RequestMapping(value = "/soa/test")@Api(value="TestController",description="测试接口描述")public class TestController {/* * @ApiOperation(value = "接口说明", httpMethod ="接口请求方式", response ="接口返回参数类型", notes ="接口发布说明" *  * @ApiParam(required = "是否必须参数", name ="参数名称", value ="参数具体描述" */@RequestMapping(value = {""})@ApiOperation(value="接口说明(测试)",httpMethod="GET",notes="在没有会话、没有签名的情况下,进入方法体")public void test(HttpServletRequest request, HttpServletResponse response, Model model) {try {response.getWriter().write("ignoreAll");} catch (IOException e) {e.printStackTrace();}}}

Several annotations in the above code need to be explained:

    • The API indicates the interface class that is available for swagger display, and value represents the description of the interface class (this annotation of the controller class can be added without adding this annotation to show the description of the interface Class)
    • Apioperation indicates that this method is intended for swagger display of interface methods, value and other meanings in detail can be seen in the above code comments
    • The arguments in the Apiparam method are only added with this annotation in order to display the Chinese description, otherwise only the English
5. Configuration of static resource files

Copy the latest version of Swagger-ui mentioned in step 2 to your Javaweb project

If you are using the Jeesite framework, you can copy it to the static directory, such as Static\swagger, or you can copy it to the Web-inf directory, such as Web-inf\swagger, At this point, however, you need to handle static file filtering in the Springmvc configuration file, such as <mvc:resources mapping= "/swagger/**" location= "/web-inf/swagger/"/>

6. Start the application server

Open the browser, access the swagger directory of index.html, you can see the beautiful interface document presented in front of you.

















Want more? Ok,that Is it

1, how to Chinese/show Chinese

The Swagger-ui itself is multi-lingual, with a piece of code in index.html:

<!-- Some basic translations -->  <!-- <script src=‘lang/translator.js‘ type=‘text/javascript‘></script> -->  <!-- <script src=‘lang/ru.js‘ type=‘text/javascript‘></script> -->  <!-- <script src=‘lang/en.js‘ type=‘text/javascript‘></script> -->

Everyone just need to open the note, and add the corresponding Chinese JS can be, the final modification as follows:

<!-- Some basic translations -->  <script src=‘lang/translator.js‘ type=‘text/javascript‘></script>  <script src=‘lang/zh-cn.js‘ type=‘text/javascript‘></script>  <!-- <script src=‘lang/en.js‘ type=‘text/javascript‘></script> -->

2, in Swagger-ui the default parameters of the content type is Application/json, test found that the background parameters did not receive the value, how to do?

You might ask, what is the effect of Content type Application/json, and why should it be modified for others? Here will be involved in the SPRINGMVC will request to pass over the parameters injected into the controller method corresponding to the principle of the object, the specific knowledge you can search, this is not the focus of this article I will not talk about, in fact, we usually write the controller method, the default content The type is actually application/x-www-form-urlencoded, and the default content type of the parameter in swagger is Application/json, which causes the swagger test to be used. The corresponding parameter submitted to the Controller method could not be injected correctly.


    • So, how to deal with it, can you change it to another?

In fact, in the swagger-ui issues, someone mentioned, https://github.com/swagger-api/swagger-ui/issues/658, the solution is to set consumes this east.

    • The solution has been found, where is the consumes set?

The answer is to set the @apioperation in this annotation and change the consumes to "application/x-www-form-urlencoded", for example:

@ApiOperation(value="接口说明(测试)",httpMethod="GET",consumes="application/x-www-form-urlencoded",notes="在没有会话、没有签名的情况下,进入方法体")

    • So under what circumstances, the content type of the parameter is Application/json?

When you add a @requestbody annotation to the parameter, it means that this parameter receives JSON data, so you can write consumes as Application/json.

3, want to know apioperation annotation HttpMethod and other parameters can write which values?

This look at the API documentation, provide an address to everyone: http://docs.swagger.io/swagger-core/apidocs/com/wordnik/swagger/annotations/ApiOperation.html

Do you have more questions? Welcome message discussion.

Build "1, integrated swagger" based on the rest service framework under SPRINGMVC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.