基礎部分
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類上的靜態方法直接完成。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
// 把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
實戰部分
1、pom.xml 中引入spring mvc、 fastjson 依賴
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
<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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
<!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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
<?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:學歷(枚舉類)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
|
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" ) @responsebody public 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" ) @responsebody public 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" ) @responsebody public 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" ) @responsebody public 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" ) @responsebody public 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> -> json string 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 -> json string 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 -> json string[] hobbies = { "a" , "b" , "c" }; string hobbiesstring = json.tojsonstring(hobbies, true ); system.out.println(hobbies); // json -> array jsonarray jsonarray = json.parsearray(hobbiesstring); for (object o : jsonarray) { system.out.println(o); } system.out.println(jsonarray); return jsonstring; } } |
swagger集成
第一步:引入相關依賴
1
2
3
4
5
6
7
8
9
10
11
|
<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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
@configuration @enablewebmvc @enableswagger2 public class swaggerconfig { @bean public 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" , //termsofserviceurl contact, //作者 "api接口" , //鏈接顯示文字 "http://www.baidu.com" //網站鏈接 ); } } |
注意:因swaggerconfig這個類配置了注解,所以這個類必須被掃描到,即該類一定包含在context:component-scan中。
第三步:在類、方法、參數上使用注解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
@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;" }) @responsebody public 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;" }) @responsebody public 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;" }) @responsebody public string getuserlist(pager pager){ return "[{'id': " +pager.getpage()+ ", 'username': 'zhangsan" +pager.getsize()+ "'}]" ; } @requestmapping ( "/docs" ) @apiignore public string test(){ return "api-docs" ; } } |
pager
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
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內容,證明正常
第五步:下載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中的腳本部分
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
<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 }); //這里可以添加權限認證,例如token function 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處理器
1
2
|
<!-- 過濾靜態資源 --> <mvc: default -servlet-handler/> |
2、 在web.xml中增加要過濾的靜態文件
1
2
3
4
5
6
7
8
|
<!-- 過濾靜態資源 --> <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> |
示例項目代碼結構:
完整示例demo下載地址:platform-springmvc-webapp.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中配置它的位置
1
2
3
4
5
6
7
8
9
|
<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,
靜態資源映射
1
2
3
4
5
6
|
<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中配置
1
2
3
4
|
<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
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:https://blog.csdn.net/vbirdbest/article/details/72472149