Spring MVC Integration Swagger detailed practice, Cliff original, refreshing feeling.

Source: Internet
Author: User
Tags documentation java web

is generally in the already very good project inside, to integrate this swagger, I this on the contrary, carefully see what this swagger depend on what jar package.
Let you have a good understanding of this thing, there are some problems, can also be simple to deal with.
I'm going to integrate this swagger practice record on the basis of a very simple MAVEN Hello World project.
So, you have to have a simple project like this.
I have the previous links, can be used for the small white reference.

First, create a simple Hello World Maven Web project, see the links below.

IntelliJ idea Create Hello World Java Web maven project from beginning to end there is a picture of the truth 2017 version

Then you add the spring MVC-related stuff to the simple project above. See the links below.

Java SPRINGMVC Web project, the Hello World entry-level project based on Maven uses the IntelliJ idea 2017 version

After the 2 links above have been carefully practiced, it's OK to get ready for work .

Start, How to integrate this swagger

first, Pom.xml's dependency dependencies are added.

In order to see the whole picture, I put all the dependence on this, because it is a super simple project, so this relies on very little, convenient audience, look at clearly, each dependence is what.

    <dependencies> <!--Spring MVC support--> <dependency> <groupid>o Rg.springframework</groupid> <artifactId>spring-webmvc</artifactId> <version&
            Gt;4.1.4.release</version> </dependency> <!--jstl--> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <ver Sion>1.2</version> <scope>runtime</scope> </dependency> <!--swa Gger2 Core Reliance--> <dependency> <groupId>io.springfox</groupId> <artif Actid>springfox-swagger2</artifactid> <version>2.6.1</version> </dependency&gt
        ; <!--Swagger-ui interface--> <dependency> <groupid>io.springfox</groupid& to provide API presentation and testing for the project
          Gt  <artifactId>springfox-swagger-ui</artifactId> <version>2.6.1</version> </ Dependency> <!--integration Swagger, the lack of this jar pack is not OK--> <dependency> <groupid>c Om.fasterxml.jackson.core</groupid> <artifactId>jackson-databind</artifactId> &L T;version>2.2.3</version> </dependency> </dependencies>

I see some old iron article inside, swear to say, old simple, need to specially introduce springfox-swagger2 and springfox-swagger-ui 2 jar Dependence, is the front of the two, Without my third in this place.

Maybe he's not, starting with a completely clean project, and he's got a third dependency on the project that I've provided above.

If, you feel wet chest I said there is a problem, you can experiment A, put me behind that dependency deleted, test. You'll find that the index page runs fine, but when you visit the controller you wrote, it blows up. I have the following error chart, for your reference.

You can see there's a missing one,

And then give the audience a look, when you add the three dependencies on the entire project, the dependency graph for each jar package .

Note that some of the old iron against the wet chest of the picture above the word is too small , alas, this can blame me ...

You can, according to my diagram operation, on the New tab, open the diagram, you can see the big picture.

This allows you to see the dependencies of each jar bundle within the Spring MVC project.

If you still want to be small, old iron, you down, you can enlarge to see it.

is not a refreshing feeling, estimated before who's article, are not so intuitive to tell you, a project of the jar package is the dependency between the bar.

Want to know how this dependency graph above comes from.

IntelliJ idea how to view a dependency graph for all jar packages in a MAVEN project
then it's Spring-servlet.xml

Need to add a sentence

<mvc:default-servlet-handler/>

In order to show the problem clearly, I'll post all of mine.

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" Xmlns:xs I= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc= "Http://www.springframework.org/schema/mvc" Xmlns:co ntext= "Http://www.springframework.org/schema/context" xsi:schemalocation= "Http://www.springframework.org/schema /beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/ MVC http://www.springframework.org/schema/mvc/spring-mvc.xsd Http://www.springframework.org/schema/context http:/ /www.springframework.org/schema/context/spring-context-3.0.xsd "> <!--to open spring Scan injection using the following annotations--> <!--@ Component, @Repository, @Service, @Controller--> <context:component-scan base-package= "com.lxk"/> <!--Open The SPRINGMVC annotation driver allows URLs to be mapped to the corresponding controller--> <mvc:annotation-driven/> <mvc:default-servlet-handler
    T <!--view Resolution--> &LT;bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name= "prefix" va Lue= "/web-inf/views/"/> <property name= "suffix" value= ". jsp"/> </bean> </beans>
Inside are some of the configurations associated with the Spring MVC project, plus a configuration that the plug-in needs.

Some old iron says that if the project is configured with interceptors, some of the following configurations need to be added,

            <mvc:exclude-mapping path= "/swagger*/**"/>
            <mvc:exclude-mapping path= "/v2/**"/> <mvc
            : Exclude-mapping path= "/webjars/**"/>
But I configured the Interceptor, but, do not configure this, the page is OK, so, this estimate depends on the personal situation.


I comment out, the page can still OK.

Finally, it is the actual operation of Java code. Divided into 2 parts, one is the configuration of Java, one is the actual you need to improve those information.

Package com.lxk.utils;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;
Import ORG.SPRINGFRAMEWORK.WEB.SERVLET.CONFIG.ANNOTATION.ENABLEWEBMVC;
Import Springfox.documentation.builders.ApiInfoBuilder;
Import springfox.documentation.builders.RequestHandlerSelectors;
Import Springfox.documentation.service.ApiInfo;
Import Springfox.documentation.service.Contact;
Import Springfox.documentation.spi.DocumentationType;
Import Springfox.documentation.spring.web.plugins.Docket;

Import Springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @author lxk on 2017/12/18/@Configuration @EnableSwagger2 @EnableWebMvc public class Apiconfig {@Bean p Ublic Docket API () {return new docket (documentationtype.swagger_2). Select (). API
    S (Requesthandlerselectors.any ()). Build (). Apiinfo (Apiinfo ()); Private Apiinfo Apiinfo () {return nEW Apiinfobuilder (). Title ("Swagger Interface Test"). Description ("Wen DAO has successively, the technique profession has specialized." "). Termsofserviceurl (" Http://blog.csdn.net/qq_27093465?viewmode=contents "). Contact (New C Ontact ("csdn eldest brother", "http://blog.csdn.net/qq_27093465", "cmshome@163.com")). License (""). Li
    Censeurl (""). Version ("1.0.0"). Build (); }

}
This inside of each description and the final page of the corresponding relationship, a look at the results of the operation of the diagram will know.

At the end of the controller is the use of annotations in the request, to perfect the final result chart.

Package Com.lxk.controller;
Import com.lxk.model.Student;
Import Com.lxk.service.StudentService;
Import Io.swagger.annotations.ApiImplicitParam;
Import Io.swagger.annotations.ApiImplicitParams;
Import io.swagger.annotations.ApiOperation;
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.RequestMethod;
Import Org.springframework.web.bind.annotation.ResponseBody;

Import Org.springframework.web.servlet.ModelAndView;

Import Javax.annotation.Resource; /** * Created by lxk on 2017/3/27/@Controller @RequestMapping ("Student") public class Studentcontroller {@Resou

    RCE (name = "Studentservice") private Studentservice Studentservice; @ResponseBody//(before I added this annotation, resulting in page access has been 406 error, the comment is good, specifically why I do not know for the time being) @ApiOperation (value = "Get all Student Object List", notes = " Get request, query all the students. ") @RequestMapping (value ="/getallstudent', method = Requestmethod.get ' public Modelandview getallstudent () {Modelandview Mav = new Modelandview ();
        Mav.setviewname ("Studentdisplay");
        Mav.addobject ("Students", Studentservice.getallstudent ());
    return MAV; @ApiOperation (value = "Get information for a single student according to the student's name", notes = "Query the student's object for information based on the student's name.") ") @ApiImplicitParam (name =" Name ", value =" Student's name ", required = true, DataType =" String ") @ResponseBody @Requ
        Estmapping (value = "Getstudentbyname", method = requestmethod.post) public String getstudentbyname (string name) {
    Return ""; @ApiOperation (value = "Get information for a single student based on the name and age of the student", notes = "Query the student object for information based on the student's name and age.")
            ") @ApiImplicitParams ({@ApiImplicitParam (name =" Name ", value =" Student Name ", required = true, DataType =" String "), @ApiImplicitParam (name = "Age", value = "Student Ages", required = true, DataType = "int")}) @ResponseBody @RequestMa
Pping (value = "Getstudentbynameandage", method = Requestmethod.post)    public string Getstudentbyname (string name, int age) {return ""; @ApiOperation (value = new Student object to database, notes = new data to database. ") @ApiImplicitParam (name =" Student ", value =" Student Object ", required = true, DataType =" student ") @ResponseBody @R Equestmapping (value = "Createnewstudent", method = requestmethod.post) public String Create (@RequestBody Student stude
    NT) {return ""; }
}
All OK, then, configure Tomcat, then start the server, then, jump to the index page, and then, open the link to the page;

http://localhost:8080/lxk/swagger-ui.html#/

The lxk of this place, is when I configure Tomcat to configure, you adapt to local conditions oh.

Then you run the result diagram.


This is the final result of execution.

The arrow on the diagram is a message that has just been written in 2 places in the Java code.

And Ah, these requests can be ordered open, there are details. When the old iron practice, can be opened to see. I don't have a screenshot.

At this point, the integration of the practice, even finished.


Say the feeling:

This thing is not very good, just say, as a developer, you save the time to write development documents, but this page came out, not very useful. What's more, the annotations you add to the controller, and the parameters used on the annotations, which are the descriptive information you write, are not related to the logic of the Code, and the advanced point of the term is this very intrusive, very unfriendly. We also say that the leader wants us to develop the writing development document, what request, the request parameter, all return what, all is what, what request method and so on this information. Because the writing and maintenance of this document is cumbersome, you intend to use this swagger plug-in to simplify this work. But I don't think it's a good thing. very bad . Personally, I think so.


I finished writing the article, to give myself a little praise, not too much,

But I'm going to order it.

I'll start with a toast, you're free. Everyone is free. Don't be polite ...


want the source code?

It's not free, you know.

I heard that some old iron, to thank the next big Bro. Sweep and get a red envelope. By the way, how about.

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.