Spring MVC+FastJson+Swagger集成的完整实例教程

本文讲解"Spring MVC+FastJson+Swagger集成的完整实例教程",用于解决相关问题。

基础部分

1. FastJson 简介

Fastjson是一个Java库,可用于将Java对象转换为JSON表示。它也可以被用来将一个JSON字符串转换成一个等效的Java对象。在转换速度上应该是最快的,几乎成为了项目的标配(在ajax请求和接口开发时一般都会用fastjson而不再使用jackson)。

GitHub: https://github.com/alibaba/fastjson (本地下载)

特性:

  • 在服务器端和android客户端提供最佳性能
  • 提供简单toJSONString()和parseObject()方法的Java对象转换为JSON,反之亦然
  • 允许存在的无法改变的对象转换为从JSON
  • Java泛型的广泛支持
  • 允许自定义表示对象
  • 支持任意复杂的对象(深继承层次结构和广泛使用泛型类型)

主要特点:

  • 快速FAST (比其它任何基于Java的解析器和生成器更快,包括jackson)
  • 强大(支持普通JDK类包括任意Java Bean Class、Collection、Map、Date或enum)
  • 零依赖(没有依赖其它任何类库除了JDK)
  • 支持注解

2. fastjson api

Fastjson API入口类是com.alibaba.fastjson.JSON,常用的序列化操作都可以在JSON类上的静态方法直接完成。

// 把JSON文本parse为JSONObject或者JSONArray 
public static final Object parse(String text); 

// 把JSON文本parse成JSONObject 
public static final JSONObject parseObject(String text); 

// 把JSON文本parse为JavaBean 
public static final <T> T parseObject(String text, Class<T> clazz); 

// 把JSON文本parse成JSONArray 
public static final JSONArray parseArray(String text); 

// 把JSON文本parse成JavaBean集合 
public static final <T> List<T> parseArray(String text, Class<T> clazz); 

// 将JavaBean序列化为JSON文本 
public static final String toJSONString(Object object); 

// 将JavaBean序列化为带格式的JSON文本 
public static final String toJSONString(Object object, boolean prettyFormat); 

// 将JavaBean转换为JSONObject或者JSONArray
public static final Object toJSON(Object javaObject); 

JSONArray:相当于List<Object>

JSONObject:相当于Map<String, Object>

SerializeConfig: 是对序列化过程中一些序列化过程的特殊配置, 如对一些字段进行格式处理(日期、枚举等)

SerializeWriter:相当于StringBuffer

SerializerFeature属性 :

  • QuoteFieldNames 输出key时是否使用双引号,默认为true
  • UseSingleQuotes 使用单引号而不是双引号,默认为false
  • WriteMapNullValue 是否输出值为null的字段,默认为false
  • WriteEnumUsingToString Enum输出name()或者original,默认为false
  • UseISO8601DateFormat Date使用ISO8601格式输出,默认为false
  • WriteNullListAsEmpty List字段如果为null,输出为[],而非null
  • WriteNullStringAsEmpty 字符类型字段如果为null,输出为”“,而非null
  • WriteNullNumberAsZero 数值字段如果为null,输出为0,而非null
  • WriteNullBooleanAsFalse Boolean字段如果为null,输出为false,而非null
  • SkipTransientField 如果是true,类中的Get方法对应的Field是transient,序列化时将会被忽略。默认为true
  • SortField 按字段名称排序后输出。默认为false
  • WriteTabAsSpecial 把\t做转义输出,默认为false 不推荐
  • PrettyFormat 结果是否格式化,默认为false
  • WriteClassName 序列化时写入类型信息,默认为false。反序列化是需用到
  • DisableCircularReferenceDetect 消除对同一对象循环引用的问题,默认为false
  • WriteSlashAsSpecial 对斜杠'/'进行转义
  • BrowserCompatible 将中文都会序列化为\uXXXX格式,字节数会多一些,但是能兼容IE 6,默认为false
  • WriteDateUseDateFormat 全局修改日期格式,默认为false。JSON.DEFFAULT_DATE_FORMAT = “yyyy-MM-dd”;JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat);
  • DisableCheckSpecialChar 一个对象的字符串属性中如果有特殊字符如双引号,将会在转成json时带有反斜杠转移符。如果不需要转义,可以使用这个属性。默认为false
  • NotWriteRootClassName 含义
  • BeanToArray 将对象转为array输出
  • WriteNonStringKeyAsString
  • NotWriteDefaultValue
  • BrowserSecure
  • IgnoreNonFieldGetter
  • WriteEnumUsingName

实战部分

Spring MVC+FastJson+Swagger集成的完整实例教程

1、pom.xml 中引入spring mvc、 fastjson 依赖

<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>com.mengdee</groupId><artifactId>platform-springmvc-webapp</artifactId><packaging>war</packaging><version>0.0.1-SNAPSHOT</version><name>platform-springmvc-webapp Maven Webapp</name><url>http://maven.apache.org</url>
<properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><junit.version>3.8.1</junit.version><log4j.version>2.5</log4j.version><jstl.version>1.2</jstl.version><spring.version>4.2.3.RELEASE</spring.version><fastjson.version>1.2.32</fastjson.version>
</properties>
<dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency>
<dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>${jstl.version}</version></dependency>
<!-- springframework --><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</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-context</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>${spring.version}</version></dependency>
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>${fastjson.version}</version></dependency>
</dependencies>
<!-- 使用aliyun镜像 --><repositories><repository><id>aliyun</id><name>aliyun</name><url>http://maven.aliyun.com/nexus/content/groups/public</url></repository></repositories>
<build><finalName>platform-springmvc-webapp</finalName></build>
</project>

2、 配置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:conf/spring/spring-*.xml</param-value></context-param>
<listener><description>Spring监听器</description><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>
<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>/WEB-INF/spring-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>
<filter><filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>

<welcome-file-list><welcome-file>/index.jsp</welcome-file></welcome-file-list>
<error-page><error-code>404</error-code><location>/index.jsp</location></error-page>
</web-app>

3、 配置spring-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:p="http://www.springframework.org/schema/p"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-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<context:component-scan base-package="com.mengdee.manage.controller" />
<bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <!-- 视图文件的前缀 --> <property name="suffix" value=".jsp"></property> <!-- 视图文件的后缀名 --> <!-- view是用什么显示,这里是jsp,还可以用velocity之类的 --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> </bean> 
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --><mvc:annotation-driven><mvc:message-converters register-defaults="true"><!-- 配置Fastjson 替换原来的jackson支持 --><bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"><property name="supportedMediaTypes"><list><value>text/html;charset=UTF-8</value><value>application/json</value></list></property><property name="features"><list>
<value>QuoteFieldNames</value> <!-- 输出key时是否使用双引号,默认为true --><value>WriteMapNullValue</value> <!-- 是否输出值为null的字段,默认为false -->
<!-- <value>DisableCircularReferenceDetect</value><value>WriteDateUseDateFormat</value> <value>WriteNullStringAsEmpty</value> 字符类型字段如果为null,输出为"",而非null <value>WriteNullNumberAsZero</value> 数值字段如果为null,输出为0,而非null <value>WriteNullBooleanAsFalse</value> Boolean字段如果为null,输出为false,而非null <value>WriteNullListAsEmpty</value> List字段如果为null,输出为[],而非null-->
</list></property></bean></mvc:message-converters></mvc:annotation-driven>
</beans> 

4、Java

Education:学历(枚举类)

package com.mengdee.manage.entity;
import java.util.HashMap;
import java.util.Map;
/*** 学历* @author Administrator**/
public enum Education {KINDERGARTEN("幼儿园", 1),ELEMENTARY("小学", 2),JUNIOR_MIDDLE("初级中学", 3),SENIOR_MIDDLE("高级中学", 4),UNIVERSITY("大学", 5),COLLEGE("学院", 6);private static final Map<Integer, Education> EDUCATION_MAP = new HashMap<Integer, Education>();static {for (Education education : Education.values()) {EDUCATION_MAP.put(education.getIndex(), education);}}
private String text;private int index;
private Education(String text, int index) {this.text = text;this.index = index;}

public String getText() {return text;}
public void setText(String text) {this.text = text;}
public int getIndex() {return index;}
public void setIndex(int index) {this.index = index;}

public static Education getEnum(Integer index) {return EDUCATION_MAP.get(index);}
}

Person:

package com.mengdee.manage.entity;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.annotation.JSONField;
public class Person {
private Long id;private String name;
private byte gender; // 性别 1:男 2:女private short age; // 年龄private long salary; // 薪水private double weight; // 体重private char level; // 评级
private boolean adult; // 是否成年人private Date birthday; // 生日private Education education;// 学历
private String[] hobbies; // 爱好private List<Dog> dogs; // 宠物狗private Map<String, Object> address; // 住址
// 使用注解控制是否要序列化@JSONField(serialize = false)private List<Object> obj = new ArrayList<>();
public Person() {
}public Person(Long id, String name, byte gender, short age, long salary, double weight, char level, boolean adult,Date birthday, String[] hobbies, List<Dog> dogs, Map<String, Object> address) {super();this.id = id;this.name = name;this.gender = gender;this.age = age;this.salary = salary;this.weight = weight;this.level = level;this.adult = adult;this.birthday = birthday;this.hobbies = hobbies;this.dogs = dogs;this.address = address;}

public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public byte getGender() {return gender;}public void setGender(byte gender) {this.gender = gender;}public short getAge() {return age;}public void setAge(short age) {this.age = age;}public long getSalary() {return salary;}public void setSalary(long salary) {this.salary = salary;}public double getWeight() {return weight;}public void setWeight(double weight) {this.weight = weight;}public char getLevel() {return level;}public void setLevel(char level) {this.level = level;}public boolean isAdult() {return adult;}public void setAdult(boolean adult) {this.adult = adult;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}
// 处理序列化枚举类型,默认的值是序列化枚举值字符串,而不是枚举绑定的索引或者文本@JSONField(name = "edu")public int getEdu(){return education.getIndex();}
@JSONField(name = "edu")public void setEdu(int index){this.education = Education.getEnum(index);}
@JSONField(serialize = false)public Education getEducation() {return education;}
@JSONField(serialize = false)public void setEducation(Education education) {this.education = education;}

public String[] getHobbies() {return hobbies;}public void setHobbies(String[] hobbies) {this.hobbies = hobbies;}public List<Dog> getDogs() {return dogs;}public void setDogs(List<Dog> dogs) {this.dogs = dogs;}public Map<String, Object> getAddress() {return address;}public void setAddress(Map<String, Object> address) {this.address = address;}
}

TestController

package com.mengdee.manage.controller;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.DoubleSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import com.mengdee.manage.entity.Address;
import com.mengdee.manage.entity.Dog;
import com.mengdee.manage.entity.Education;
import com.mengdee.manage.entity.Person;

@Controller
public class TestController {private static SerializeConfig serializeConfig = new SerializeConfig(); static {serializeConfig.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss")); serializeConfig.put(Double.class, new DoubleSerializer(new DecimalFormat("0.00")));}

@RequestMapping("/index")public String index(){return "index";}

// javabean to object@RequestMapping("/json")@ResponseBodypublic Object json(){Person person = new Person();person.setId(1L);person.setName("mengdee");person.setAge((short) 18);
// /*{"birthday": null, "weight": 0, "dogs": null, "adult": false, "hobbies": null, "education": null, "id": 1, "level": "", "address": null, "age": 18, "name": "mengdee", "gender": 0, "salary": 0}*/Object personJson = JSON.toJSON(person);return personJson;}
// javabean to string@RequestMapping("/json2")@ResponseBodypublic String json2(){Person person = new Person();person.setId(1L);person.setName("mengdee");person.setAge((short) 18);
// 使用该方式值为null的经测试不出来,已经配置了<value>WriteMapNullValue</value>
// "{"adult":false,"age":18,"gender":0,"id":1,"level":"","name":"mengdee","salary":0,"weight":0.0}"String jsonString = JSON.toJSONString(person);return jsonString;}
@RequestMapping("/json3")@ResponseBodypublic Object json3(){Person person = new Person();person.setId(1L);person.setName("mengdee");person.setAge((short) 18);person.setBirthday(new Date()); 
Object personJson = JSON.toJSON(person); // JSON.toJSON(person)默认是毫秒数"birthday":1495073314780,

// 使用serializeConfig序列号配置对日期格式化
// "{"birthday":"2017-05-18 10:19:55","weight":0.0,"adult":false,"id":1,"level":"","age":18,"name":"mengdee","gender":0,"salary":0}"String jsonString = JSON.toJSONString(personJson, serializeConfig);return jsonString;}

@RequestMapping("/json4")@ResponseBodypublic Object json4(){Person person = new Person();person.setId(1L);person.setName("mengdee");person.setAge((short) 18);person.setBirthday(new Date()); person.setEducation(Education.UNIVERSITY); // 枚举
String[] hobbies = {"读书", "旅游"};person.setHobbies(hobbies);
Dog dog1 = new Dog(1L, "dog1", (short)1);Dog dog2 = new Dog(2L, "dog2", (short)2);List<Dog> dogs = new ArrayList<>();dogs.add(dog1);dogs.add(dog2);person.setDogs(dogs);
Address address1 = new Address(1l, "上海浦东新区");Address address2 = new Address(2l, "上海宝山区");Map<String, Object> addressMap = new HashMap<>();addressMap.put(address1.getId() + "", address1);addressMap.put(address2.getId() + "", address2);person.setAddress(addressMap);


Object personJson = JSON.toJSON(person);
return personJson;}
@RequestMapping("/json5")@ResponseBodypublic String json5(){Dog dog1 = new Dog(1L, "dog1", (short)1);Dog dog2 = new Dog(2L, "dog2", (short)2);List<Dog> dogs = new ArrayList<>();dogs.add(dog1);dogs.add(dog2);
// List<T> -> JSONString jsonString = JSON.toJSONString(dogs, false);System.out.println(jsonString);
// JSON -> List<T> List<Dog> parseArray = JSON.parseArray(jsonString, Dog.class);for (Dog dog : parseArray) {System.out.println(dog);}
Map<String,Dog> map = new HashMap<String, Dog>(); map.put("dog1",new Dog(1L, "dog1", (short)1)); map.put("dog2",new Dog(2L, "dog2", (short)2)); map.put("dog3",new Dog(3L, "dog3", (short)3)); 
// Map -> JSONString mapJsonString = JSON.toJSONString(map,true); System.out.println(mapJsonString); 
// JSON -> Map @SuppressWarnings("unchecked")Map<String,Dog> map1 = (Map<String,Dog>)JSON.parse(mapJsonString); for (String key : map1.keySet()) { System.out.println(key + ":" + map1.get(key)); }
// Array -> JSONString[] hobbies = {"a","b","c"}; String hobbiesString = JSON.toJSONString(hobbies,true); System.out.println(hobbies); 
// JSON -> ArrayJSONArray jsonArray = JSON.parseArray(hobbiesString); for (Object o : jsonArray) { System.out.println(o); } System.out.println(jsonArray); return jsonString;}
}

Swagger集成

第一步:引入相关依赖

<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.6.1</version><scope>compile</scope>
</dependency>
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.6.6</version>
</dependency>

第二步:Swagger信息配置

SwaggerConfig.java

@Configuration
@EnableWebMvc
@EnableSwagger2
public class SwaggerConfig {@Beanpublic Docket customDocket() {Docket docket = new Docket(DocumentationType.SWAGGER_2);docket.apiInfo(apiInfo());docket.select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class));docket.select().paths(PathSelectors.regex("/api/.*")).build();
return docket;}
private ApiInfo apiInfo() {Contact contact = new Contact("小明", "http://www.baidu.com", "baidu@163.com");return new ApiInfo("API接口", //大标题 title"API接口", //小标题"0.0.1", //版本"www.baidu.com",//termsOfServiceUrlcontact,//作者"API接口",//链接显示文字"http://www.baidu.com"//网站链接);}
}

注意:因SwaggerConfig这个类配置了注解,所以这个类必须被扫描到,即该类一定包含在context:component-scan中。

第三步:在类、方法、参数上使用注解

@Controller
@RequestMapping("/api/v1")
@Api(description = "API接口")
public class ApiController {@ApiOperation(value = "用户登录", notes = "用户登录接口")@ApiResponses({@ApiResponse(code = 0, message = "success"),@ApiResponse(code = 10001, message = "用户名错误", response = IllegalArgumentException.class),@ApiResponse(code = 10002, message = "密码错误")})@RequestMapping(value = "/user/login", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})@ResponseBodypublic String login(@ApiParam(name = "username", value = "用户名", required = true) @RequestParam String username,@ApiParam(name = "password", value = "密码", required = true) @RequestParam String password){return "{'username':'" + username + "', 'password':'" + password + "'}";}

@ApiImplicitParams({@ApiImplicitParam(paramType = "header", name = "phone", dataType = "String", required = true, value = "手机号"),@ApiImplicitParam(paramType = "query", name = "nickname", dataType = "String", required = true, value = "nickname", defaultValue = "双击666"),@ApiImplicitParam(paramType = "path", name = "platform", dataType = "String", required = true, value = "平台", defaultValue = "PC"),@ApiImplicitParam(paramType = "body", name = "password", dataType = "String", required = true, value = "密码")})@RequestMapping(value = "/{platform}/user/regist", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})@ResponseBodypublic String regist(@RequestHeader String phone, @RequestParam String nickname, @PathVariable String platform, @RequestBody String password){return "{'username':'" + phone + "', 'nickname':'" + nickname + "', 'platform': '" + platform + "', 'password':'"+password+"'}";}
@RequestMapping(value = "/user/list", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8;"})@ResponseBodypublic String getUserList(Pager pager){return "[{'id': "+pager.getPage()+", 'username': 'zhangsan"+pager.getSize()+"'}]";}
@RequestMapping("/docs")@ApiIgnorepublic String test(){return "api-docs";}
}

Pager

public class Pager {@ApiModelProperty(value = "页码", required = true)private int page;@ApiModelProperty(value = "每页条数", required = true)private int size;
public Pager() {}
public int getPage() {return page;}
public void setPage(int page) {this.page = page;}
public int getSize() {return size;}
public void setSize(int size) {this.size = size;}
}

常用注解:

  • @Api(description = “接口类的描述”)
  • @ApiOperation(value = “接口方法的名称”, notes = “备注说明”)
  • @ApiParam(name = “参数名称”, value = “备注说明”, required = 是否必须):标注在方法的参数上 用于描述参数的名称、备注、是否必须等信息
  • @ApiImplicitParam(paramType = “query”, name = “password”, dataType = “String”, required = true, value = “密码”, defaultValue = “123456”)用于描述方法的参数,标注在方法上,和@ApiParam功能一样,只是标注的位置不同而已
         .paramType:参数类型,即参数放在哪个地方
                .   header–>请求参数的获取:@RequestHeader,参数放在请求头
                 .   query–>请求参数的获取:@RequestParam,参数追加在url后面
                 .   path(用于restful接口)–>请求参数的获取:@PathVariable
                 .   body 使用@RequestBody接收数据 POST有效,参数放在请求体中
                 .    form
        .name:参数名
        .dataType:参数的数据类型
        .required:参数是否必须传
        .value:参数的描述
        .defaultValue:参数的默认值
  • @ApiImplicitParams: 用于包含多个@ApiImplicitParam
  • @ApiResponse(code = 0, message = “success”),
         .code:响应码,例如400
         .message:信息,一般是对code的描述
         .response:抛出异常的类
  • @ApiModel:描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候)
         .@ApiModelProperty:描述一个model的属性
                  .   position 允许在模型中显式地排序属性。
                  .   value 参数名称
                  .   required 是否必须 boolean
                  .   hidden 是否隐藏 boolean
                  .   allowableValues = “range[0, 1]” 一般用于指定参数的合法值
  • @ApiIgnore:用于或略该接口,不生成该接口的文档

第四步:访问/v2/api-docs

在浏览器上访问http://localhost:8080/工程名称/v2/api-docs 如果有json内容,证明正常

Spring MVC+FastJson+Swagger集成的完整实例教程

第五步:下载swagger-ui

从github上下载https://github.com/swagger-api/swagger-ui,注意这里要选择下载v2.2.10(https://github.com/swagger-api/swagger-ui/tree/v2.2.10 (本地下载)),大于这个版本的集成方式不一样。

集成方法:将v2.2.10下的dist目录下的所有文件放到自己工程中静态文件中,并使用下面代码覆盖掉index.html中的脚本部分

<script type="text/javascript">var baseUrl = "";$(function () {var url = window.location.search.match(/url=([^&]+)/);if (url && url.length > 1) {url = decodeURIComponent(url[1]);} else {//上面描述的api-docs地址url = baseUrl + "/webapp/v2/api-docs";}
// Pre load translate...if (window.SwaggerTranslator) {window.SwaggerTranslator.translate();}window.swaggerUi = new SwaggerUi({url: url,validatorUrl: undefined,dom_id: "swagger-ui-container",supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'],onComplete: function (swaggerApi, swaggerUi) {if (typeof initOAuth == "function") { initOAuth({  clientId: "your-client-id",  clientSecret: "your-client-secret-if-required",  realm: "your-realms",  appName: "your-app-name",  scopeSeparator: ",",  additionalQueryStringParams: {} }); }if (window.SwaggerTranslator) { window.SwaggerTranslator.translate(); }$('pre code').each(function (i, e) { hljs.highlightBlock(e) });addApiKeyAuthorization();},onFailure: function (data) { log("Unable to Load SwaggerUI");},docExpansion: "none",jsonEditor: false,apisSorter: "alpha",defaultModelRendering: 'schema',showRequestHeaders: false});
//这里可以添加权限认证,例如tokenfunction addApiKeyAuthorization() {var token = "you-token";var tokenHeader = new SwaggerClient.ApiKeyAuthorization("token", token, "header");window.swaggerUi.api.clientAuthorizations.add("token", tokenHeader);}
window.swaggerUi.load();function log() {if ('console' in window) { console.log.apply(console, arguments);}}});</script>

第六步:访问上面修改的那个index.html
http://localhost:8080/工程名称/static/third-party/swagger-ui/index.html

注意:因要访问静态资源,使用springmvc请确保静态资源能够被访问到,如果不能访问请做如下配置:

1、 在Spring的配置文件中增加默认的servlet处理器

<!-- 过滤静态资源 -->
<mvc:default-servlet-handler/>

2、 在web.xml中增加要过滤的静态文件

<!-- 过滤静态资源 -->
<servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.js</url-pattern><url-pattern>*.css</url-pattern><url-pattern>/assets/*"</url-pattern><url-pattern>/images/*</url-pattern>
</servlet-mapping>

Spring MVC+FastJson+Swagger集成的完整实例教程

示例项目代码结构:

Spring MVC+FastJson+Swagger集成的完整实例教程

完整示例Demo下载地址: http://xiazai.jb51.net/201804/yuanma/platform-springmvc-webapp(jb51.net).rar

其他

关于spring-servlet.xml 和 applicationContext.xml

SpringMVC 提供了两种配置文件 spring-servlet.xml 、 applicationContext.xml
spring-servlet.xml 是Controller级别的,作用范围是控制层,默认的名字是【servlet-name】-servlet.xml
默认是放在WEB-INF/目录下,SpringMVC会自动加载,也可以在web.xml中配置它的位置

<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>/WEB-INF/spring-servlet.xml</param-value> </init-param><load-on-startup>1</load-on-startup>
</servlet>

一般在spring-servlet.xml中配置一些和控制器相关的配置,如视图解析、静态资源文件的映射、返回结果的解析等

视图解析

  • org.springframework.web.servlet.view.UrlBasedViewResolver
  • tiles3: org.springframework.web.servlet.view.tiles3.TilesConfigurer
  • springMVC: org.springframework.web.servlet.view.InternalResourceViewResolver,
  • shiro: org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor
  • 上传 org.springframework.web.multipart.commons.CommonsMultipartResolver,

静态资源映射

<mvc:resources location="/static/" mapping="/static/**" />
<mvc:resources location="/images/" mapping="/static/**" />
<mvc:resources location="/css/" mapping="/static/**" />
<mvc:resources location="/js/" mapping="/static/**" />
<mvc:resources location="/html/" mapping="/static/**" /> 
<mvc:resources location="/upload/" mapping="/static/**" />

org.springframework.context.support.ResourceBundleMessageSource

返回结果的解析

  • FastJson: com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter

3、applicationContext.xml 是系统级别的配置,作用范围是系统上下文,它的初始化需要放到 web.xml 中的context-param中配置

<context-param><param-name>contextConfigLocation</param-name><param-value>classpath:conf/spring/spring-*.xml</param-value>
</context-param>

4、 关于applicationContxt.xml,一般是按照功能拆成多个配置文件如:

  • - applicationContxt-base.xml // 基础
  • - applicationContxt-redis.xml // redis相关配置
  • - applicationContxt-shiro.xml // shiro 相关配置
  • - applicationContxt-dao.xml // 数据库相关配置
  • - applicationContxt-xxx.xml // xxx

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对亿速云的支持。

关于 "Spring MVC+FastJson+Swagger集成的完整实例教程" 就介绍到此。希望多多支持编程宝库

SpringMVC如何整合SpringSession实现sessiong:本文讲解"SpringMVC怎么整合SpringSession实现sessiong",用于解决相关问题。一、在pom.xml添加springSession<!- ...