基本部品
1。Fastjsonの紹介
FastJsonは、JavaオブジェクトをJSON表現に変換するために使用できるJavaライブラリです。また、JSON文字列を同等のJavaオブジェクトに変換するためにも使用できます。これは最も速い変換速度である必要があり、プロジェクトの標準構成となっています(Ajaxリクエストとインターフェイス開発の場合、通常はJacksonの代わりにFastjsonが使用されます)。
github:https://github.com/alibaba/fastjson(ローカルダウンロード)
特性:
主な機能:
2。FastJSONAPI
FastJson APIエントリクラスはcom.alibaba.fastjson.jsonです。一般的なシリアル化操作は、JSONクラスの静的メソッドによって直接完了できます。
// jsonobjectまたはjsonarray public static final object parse(string text)としてJSONテキストを解析します。 // json textにjsonobject public static final jsonobject parseobject(string text)にparse jsonテキスト。 // json text as javabean public static final <t> t parseobject(string text、class <t> clazz); // json text into jsonarray public static final jsonarray parsearray(string text)にparse jsonテキスト。 // JSONテキストをJavabean Collection Public Static Final <t> list <t> parsearray(string text、class <t> clazz)に解析します。 // javabeanをJSONテキストにシリアル化して、public static final string tojsonstring(object object); // javabeanをフォーマットしたjsonstring(object object、boolean preticformat)にシリアル化します。 // javabeanをjsonobjectまたはjsonarraypublic static final object tojson(object javaobject)に変換します。
JSonArray:list <Object>に相当します
JSonObject:Map <String、Object>に相当します
Serializeconfig:シリアル化プロセス中のいくつかのシリアル化プロセスの特別な構成(一部のフィールド(日付、列挙など)のフォーマットなど)
SerializeWriter:StringBufferに相当します
SerializerFeatureプロパティ:
実用的な部分
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.apach/4.0. http://maven.apache.org/maven-v4_0_0.xsd "> <modelversion> 4.0.0 </modelversion> <groupid> com.mengdee </groupid> <artifactid> platform-springmvc-webapp </artifactid> <バージョン< <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> <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> <redency> <redency> <redency> <empricage> <Artifactid> junit </artifactid> <バージョン> 3.8.1 </version> <scope>テスト</scope> </dependency> <dependency> <expendency> <groupid> javax.servlet </groupid> <artifactid> jstl </artifactid> <バージョン> $ {jstl.version} <groupid> org.springframework </groupid> <artifactid> spring-webmvc </artifactid> <bersion> $ {spring.version} </version> </dependency> <sependency> <shiplency> <groupid> org.springframework </groupid> <artifactid> spring <Dependency> groupId> org.springframework </groupid> <artifactid> spring-context </artifactid> <version> $ {spring.version} </version> </dependency> <sependency> <sheplency> <groupid> org.springframework </groupid> <artifactid> spring-copport </artifictid> <バージョン> $ {spring.version} </version> </dependency> <dependency> <shipid> org.springframework </groupid> <artifactid> spring-jdbc </artifactid> <version> $ {spring.version} </version> </dependency> <seplency> com.al.alid> </groupid> </</<> <> <artifid <バージョン> $ {fastjson.version} </version> </dependency> </dependencies> <! - aliyun mirror-> <positories> <repository> <id> aliyun </id> <name> aliyun </name> <url> http://maven.aliyun.com/nexus/content/content/grupsig </repository> </repository> </repository> <build> <finalName> Platform-springMvc-Webapp </finalName> </build> </project>2。web.xmlを構成します
<!doctype web-app public " - // Sun Microsystems、Inc .//dtd Webアプリケーション2.3 // en" "http://java.sun.com/dtd/web-app> <dispal-name> archeType作成されたWebアプリケーション</<contation-name> <conttunce-name> <permam> <param> <param> <param> <param <param-value> classpath:conf/spring/spring-*。xml </param-value> </context-param> <リスナー> <説明> springリスナー</descrips> <リスナークラス> org.springframework.web.context.contextloaderlistener </ristener-class> <Servlet-Class> org.springframework.web.servlet.dispatcherservlet </servet-class> <init-param> <param-name> contextconfiglocation </param-name> <param-value> /web-inf/spring-servlet.xml </param-> serv-on-start> <サーブレットマッピング> <サーブレットマッピング> <Servlet-Name> spring-mvc </servlet-name> <url-pattern>/</url-pattern> </servet-mapping> <filter> <filter-name> charaterecodingfilter </filter-name> <filter-class> org.springframework.filtter.cherecterencedingfilter <param-name> encoding </param-name> <param-value> utf-8 </param-value> </init-param> <init-param> <param-name> forceConding </param-name> <param-value> true </param-value> </init-param> </filter> <filter-name> <filter-name> <filter-name </filter-namin <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> </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 = " xsi:schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.2.xsd http://www. 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ベースパッケージ=" com.mengdee.manage.controller "/> <bean id =" viewresolver "> <property = << name = "suffix" value = "。jsp"> </property> <! - suffix name = "! - 表示に使用されるビューは何ですか?ここではjspです。リクエストと注釈のマッピングPojos-> <MVC:Annotation-Driven> <MVC:Message-Converters Register-Defaults = "True"> <! - 元のジャクソンサポートを置き換えるようにfastJsonを構成 - > <bean> <プロパティ名= "supportedmediatypes"> <リスト> <値> <価値> < </list> </property> <property name = "feature"> <list> <value> quotefieldnames </value> <! - キーを出力するときに二重引用符を使用するかどうか、デフォルト - > <値> writemapnullvalue </value> <! <value> writedAteUsedAteFormat </value> <value> writenullstringasempty </value>文字型フィールドがnullの場合、出力はnull <value> writenullnumberaszero </value>である場合、数値フィールドがnullの場合、出力が0、null <balue> valueanasfals <value> writenulllistasempty </value>リストフィールドはnull、outputは[]、null-> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> </bean>
4。Java
教育:教育(列挙クラス)
パッケージcom.mengdee.manage.entity; import java.util.hashmap; import java.util.map;/** * ducations * @author Administrator * */public enum Education {kindergarten "、1)、Elementary("小学校 "、2)、ジュニア_middle大学(「大学」、5)、大学(「大学」、6);プライベート静的最終マップ<integer、教育> education_map = new Hashmap <integer、Education>(); static {for(Education Education:Education.Values()){Education_Map.put(Education.getIndex()、Education); }} private文字列テキスト;プライベートインデックス;私立教育(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); }}人:
パッケージcom.mengdee.manage.entity; import java.util.arraylist; Import java.util.date; Import java.util.list; import java.util.map; import com.alibaba.annotation.annotation.annotation.jsonfield; public class person {private long id;プライベート文字列名;プライベートバイト性別。 //性別1:男性2:女性のプライベートショート年齢。 //年齢のプライベート給与。 //給与プライベートダブルウェイト。 //重量のプライベートチャーレベル。 //プライベートブールアダルトの評価。 //大人のプライベートデートの誕生日かどうか。 //誕生日私立教育教育; //教育資格プライベートストリング[]趣味。 //趣味のプライベートリスト<Dog> Dogs; //ペットドッグプライベートマップ<文字列、オブジェクト>アドレス; //アドレス//アノテーションを使用して、@jsonfield(serialize = false)private list <object> obj = new ArrayList <>(); public Person(){} public Person(長いID、文字列名、バイトの性別、短い年齢、長い給与、二重重量、charレベル、ブールアダルト、日付の誕生日、弦、趣味、リスト<犬>犬、地図<文字列、オブジェクト>アドレス){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 =趣味; 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(短い年齢){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 enducation.getIndex(); } @jsonfield(name = "edu")public void setedu(int index){this.education = education.getEnum(index); } @jsonfield(serialize = false)公教育geteducation(){return suduce; } @jsonfield(serialize = false)public void seteducation(教育教育){this.education = education; } public string [] gethobbies(){return Hobbies; } public void sethobbies(string []趣味){this.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
パッケージcom.mengdee.manage.controller; import java.text.decimalformat; import java.util.arraylist; import java.util.date; import java.util.list; import java.util.map; import java.util.map; springframework.web.bind.annotation.requestmapping; Import org.springframework.web.bind.annotation.responsebody; Import com.alibaba.fastjson.json; Import com.alibaba.fastjson.jsonarray; Import com.aliba.aliba.fastjson.duesierizerializerizer com.alibaba.fastjson.serializer.serializeconfig; Import com.alibaba.fastjson.serializer.simpledateformatserializer; Import com.mengdee.manage.entity.Address; Import com.mengdee.manage.entity.dog; Import.mengdee.Manage.Entiity com.mengdee.manage.entity.person; @controllerpublic 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); /// * {「誕生日」:null、 "weight"、 "dogs":null、 "null":false、 "趣味、null、「教育」:null、" null、 "id":1、 "level": ""、 "dresd":null、 "null、" null、 "null、" null、 "age":age ":age":18、 "name": "mengdee"、 "person":0、 " 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 = jsonstring(person); 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(人)デフォルトでミリ秒「誕生日」:1495073314780、// serializeconfigシリアル番号を使用して日付のフォーマットを構成する// "{"誕生日 ":" 2017-05-18 10:19:55 "、" weight ":0.0、" adult ":false、" id ":1、" level ":" "、" age ":18、" name ":" mengdee "、" jender ":0、" salary ":0}" 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); //列挙文字列[]趣味= {"reading"、 "Tourism"}; person.seThobbies(趣味); 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(犬);アドレスアドレス1 =新しいアドレス(1L、「上海プードン新しい地区」);アドレスアドレス2 =新しいアドレス(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); 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(犬犬: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(趣味、真); System.out.println(趣味); // json-> array jsonarray jsonarray = json.parsearray(hobbiesstring); for(object o:jsonarray){system.out.println(o); } system.out.println(jsonarray); jsonstringを返します。 }}Swagger統合
ステップ1:関連する依存関係を紹介します
<Dependency> GroupId> io.springfox </groupid> <artifactid> springfox-swagger2 </artifactid> <version> 2.6.1 </version> <scope> compile </scope> </dependency> <依存関係> <groupid> com.fasterxml.jackson.core </groupid> </groupid> </groupid> </groupid> </groupid> </groupid> </groupid> </groupid> < <バージョン> 2.6.6 </version> </dependency>
ステップ2:情報構成をSwagger
swaggerconfig.java
@configuration@enablewebmvc@enableswagger2public class swaggerconfig {@bean public docket customdocket(){docket docket = new Docket(documentationType.swagher_2); docket.apiinfo(apiinfo()); docket.select()。 docket.select()。paths(pathselectors.regex( "/api/.*"))。build();ドケットを返します。 } private apiinfo apiinfo(){contact contact = new contact( "xiao ming"、 "http://www.baidu.com"、 "[email protected]");新しいapiinfo( "APIインターフェイス"、//ビッグタイトル "APIインターフェイス"、// subtitle "0.0.1"、// version "www.baidu.com"、//項著者 "APIインターフェイス"、//リンク表示テキスト "http://ww.baidu.com }}注: swaggerconfigクラスはアノテーションを構成するため、このクラスはスキャンする必要があります。つまり、クラスはコンテキストに含める必要があります:Component-Scan。
ステップ3:クラス、方法、およびパラメーターで注釈を使用します
@controller @requestmapping( "/api/v1") @api(description = "api interface")public class apicontroller {@apioperation(value = "user login"、notes = "user login interface")@apiresponses({@apiresponse(code = 0、message = "" success ") Illegalargumentexception.class)、@apireSponse(code = 10002、message = "password error")})@requestmapping(value = "/user/login"、method = requestmethod.post、produces = {"application/json; charset = utf-8;"})@responsebody body body public string login(bult = " = true)@RequestParam String username、@Apiparam(name = "password"、value = "password"、必須= true)@requestparam文字列パスワード){return "{'username': '" + username + "'、 'password': '" + password + "'}"; } @apiimplicitparams({@apiimplicitparam(paramtype = "header"、name = "phone"、datatype = "string"、rebys = true、value = "携帯番号")、@apiimplicitparam(paramtype = "query"、name = "nickname"、dataType = "defaly =" defaly = "strue =" 666 ")、@apiimplicitparam(paramtype =" path "、name =" platform "、datatype =" string "、必須= true、value =" platform "、defaultvalue =" pc ")、@apiimplictparam(paramtype =" body "、name =" password "、dataType ="、 "= true =" prut = "prust") ")") "/{platform}/user/regist"、method = requestmethod.post、roduces = {"application/json; charset = utf-8;"})@responsebody public string regist( @requestparam string nickname、 @rrequestbody string platform、 @rrequestbody string prastis '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()+" 'Zhangsan "+pager.getSize()+"'}] "; } @RequestMapping( "/docs")@apiignore public string test(){return "api-docs"; }}ページャ
public class pager {@apimodelproperty(value = "ページ番号"、必須= true)private int page; @apimodelproperty(value = "ページあたりの数"、必須= true)プライベートintサイズ。 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; }}一般的な注釈:
ステップ4:アクセス /V2 /API-Docs
http:// localhost:8080/project name/v2/api-docsにアクセスしてください。JSONコンテンツがある場合は正常です
ステップ5: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 {//上記のurl = basepp/v2/v2/v2/v2/v2/basp/v2/v2/v2/v2/v2/v2/v2/v2/v2/v2/v2/v2/ (window.swaggertranslator){window.swaggertranslator.translate(); (swaggerapi、swaggerui){if(typeof initoauth == "function"){{clientid: "your-client-id"、clientret: "your-client-secret-if-if-required"、remolm (window.swaggletranslate.translate()} $(i、e){hljs.highlightblock(e)})。 Jsoneditor:apissorter: "alpha"、defaultmodelrendering: 'schema'、false}); window.api.clientauthorizations.add( "token"、tokenheader); </script>ステップ6:上記で変更されたindex.htmlにアクセスします
http:// localhost:8080/project name/static/third-party/swagger-ui/index.html
注:静的リソースにアクセスするため、SpringMVCを使用して静的リソースにアクセスできることを確認してください。アクセスできない場合は、次の構成を作成してください。
1.デフォルトのサーブレットプロセッサをスプリング構成ファイルに追加します
<! - 静的リソースをフィルター - > <MVC:デフォルトセルバーハンドラー/>
2. web.xmlでフィルタリングする静的ファイルを追加します
<! - 静的リソースのフィルタリング - > <サーブレットマッピング> <Servlet-name>デフォルト</servlet-name> <url-pattern>*。Js</url-Pattern>*。CSS</url-Pattern> <url-pattern>/assets/*"</url-pattern> <urltertn> </urltn>
サンプルプロジェクトコード構造:
デモの完全な例ダウンロードアドレス:http://xiazai.vevb.com/201804/yuanma/platform-springmvc-webapp(vevb.com).rar
他の
spring-servlet.xmlおよびapplicationContext.xmlについて
SpringMVCは、2つの構成ファイルSpring-Servlet.xmlとApplicationContext.xmlを提供します
Spring-servlet.xmlはコントローラーレベルであり、その範囲のアクションはコントロール層です。デフォルト名は[Servlet-Name] -servlet.xmlです
デフォルトでは、Web-INF/ディレクトリに配置されます。 SpringMVCは自動的にロードされ、Web.xmlで構成することもできます。
<サーブレット> servlet-name> spring-mvc </servlet-name> <servlet-class> org.springframework.web.servlet.dispatcherservlet </servlet-class> <init-param> <param-name> contextconfiglocation </param-name> <param-value> <load-on-startup> 1 </load-on-startup> </servlet>
一般に、一部のコントローラー関連の構成は、ビュー解像度、静的リソースファイルのマッピング、返品結果の解析など、Spring-Servlet.xmlで構成されています。
分析を表示します
静的リソースマッピング
<MVC:リソースlocation = "/static/" mapping = "/static/**"/> <mvc:resources location = "/" mapping = "/static/**"/> <mvc: "/css/" mapping = "/static/**"/> <mvc: "/js/> <mvc/> <mvc/> <mvc:リソース場所= "/html/" mapping = "/static/**"/> <mvc:resources location = "/upload/" mapping = "/static/**"/>
org.springframework.context.support.resourcebundlemessagesource
結果分析
3。ApplicationContext.xmlはシステムレベルの構成であり、その機能の範囲はシステムコンテキストです。その初期化は、web.xmlのコンテキストパラムで構成する必要があります。
<context-param> <param-name> contextconfiglocation </param-name> <param-value> classpath:conf/spring/spring - *。xml </param-value> </context-param>
4。AppootContxt.xmlに関しては、以下など、関数に従って複数の構成ファイルに分割されます。
要約します
上記は、この記事のコンテンツ全体です。この記事の内容には、すべての人の研究や仕事に特定の参照値があることを願っています。ご質問がある場合は、メッセージを残してコミュニケーションをとることができます。 wulin.comへのご支援ありがとうございます。