SpringMVCでは、2つのAnnotations @RequestBodyと@ResponseBodyを使用して、リクエストパケットのオブジェクトとオブジェクトへの変換をそれぞれ回答して応答パケットを完了できます。この柔軟なメッセージ変換メカニズムが使用されます。システムによって構成されたhttpmessageconverterを使用して解析し、対応するデータをオブジェクトにバインドして返すようにします。
httpinputmessage
このクラスは、SpringMVC内のHTTP要求メッセージの抽象化です。 httpmessageConverterのread()メソッドには、httpinputmessageの正式なパラメーターがあります。これは、SpringMVCのメッセージコンバーターが再生する受容体「リクエストメッセージ」の内部抽象化です。メッセージコンバーターは、ルールに従って「要求メッセージ」からメッセージを抽出し、メソッドフォーマルパラメーターで宣言されたオブジェクトに変換します。
Package org.springframework.http; import java.io.ioexception; import java.io.inputstream; public interface httpinputmessage extends httpmessage {inputstream getbody()throws ioexception;}httpoutputmessage
httpmessageConverterの書き込み()メソッドには、springMVCのメッセージコンバーターが使用する受容体「応答メッセージ」の内部抽象化であるHTTPOUTPUTMESSAGEの正式なパラメーターがあります。メッセージコンバーターは、特定のルールに従って「応答メッセージ」を応答メッセージに書き込みます。
パッケージorg.springframework.http; Import java.io.ioexception; Import java.io.outputStream; public interface httpoutputmessage extends httpmessage {outputStream getBody()Throws IOException;}httpmessageconverter
/ * * Copyright 2002-2010元の著者または著者。 * * Apacheライセンス、バージョン2.0(「ライセンス」)に基づいてライセンスされています。 *ライセンスに準拠している場合を除き、このファイルを使用することはできません。 *ライセンスのコピーを取得することができます * * http://www.apache.org/licenses/license-2.0 * *該当する法律で要求されていない場合、または書面で合意しない限り、ライセンスに基づいて配布されるソフトウェア *は、保証または条件なしで「現状」に分配されます。 *権限を管理する特定の言語のライセンスと、ライセンスに基づく制限を参照してください。 */package org.springframework.http.converter; import java.io.ioexception; import java.util.list; import org.springframework.httpinputmessage; Import org.springframework.http.httputtutmessage; Import; org.springframework.http.mediatype; public interface httpmessageconverter <t> {boolean canread(class <?> clazz、mediatype mediatype); Boolean Canwrite(class <?> clazz、mediatype mediatype);リスト<Mediatype> getSupportedmediatypes(); t read(class <?clazz、httpinputmessage inputmessage)は、ioexception、httpmessagenotreadableexceptionをスローします。 void write(t t、mediatype contentType、httpoutputmessage outputmessage)IoException、httpmessagenotwritexception;}httpmessageconverterインターフェイスは、5つの方法を提供します。
読み取りおよび書き込み方法のパラメーターには、それぞれhttpinputmessageとhttpoutputmessageオブジェクトが含まれます。これらの2つのオブジェクトは、それぞれHTTP通信の要求と応答の部分を表します。対応する入力ストリームと出力ストリームは、GetBodyメソッドを介して取得できます。
現在、次のものを含む、デフォルトでデフォルトで提供されるコンバーターがかなりあります。
| 名前 | 効果 | 読み取りサポートmediatype | サポートmediatypeを作成します |
|---|---|---|---|
| bytearrayhttpmessageconverter | データとバイト配列の変換 | / | アプリケーション/オクテットストリーム |
| stringhttpmessageconverter | データと文字列タイプの変換 | 文章/* | テキスト/プレーン |
| formhttpmessageconverter | フォームとmultivaluemap <string、string = "">の変換 | アプリケーション/x-www-form-urlencoded | アプリケーション/x-www-form-urlencoded |
| sourcehttpmessageconverter | transform.source data and javax.xml.transform.sourceのコンバージョン | テキスト/XMLおよびアプリケーション/XML | テキスト/XMLおよびアプリケーション/XML |
| marshallinghttpmessageconverter | SpringMarshaller/Unmarshallerを使用してXMLデータを変換します | テキスト/XMLおよびアプリケーション/XML | テキスト/XMLおよびアプリケーション/XML |
| mappingjackson2httpmessageconverter | JacksonのObjectMapperを使用してJSONデータを変換します | アプリケーション/JSON | アプリケーション/JSON |
| mappingjackson2xmlhttpmessageconverter | JacksonのXMLMapperを使用してXMLデータを変換します | アプリケーション/XML | アプリケーション/XML |
| bufferedimagehttpmessageconverter | データとjava.awt.image.bufferedimageの変換 | Java I/O APIでサポートされているすべてのタイプ | Java I/O APIでサポートされているすべてのタイプ |
httpmessageconverterマッチングプロセス:
@RequestBodyアノテーション:リクエストオブジェクトのヘッダー部分のコンテンツタイプのタイプに従って、適切なhttpmessageConverterを1つずつ一致させてデータを読み取ります。
プライベートオブジェクトreadwithmessageconverters(methodparameter methodparam、httpinputmessage inputmessage、class paramtype)をスロー{mediatype contenttype = inputmessage.getheaders()。getContentType(); if(contentType == null){stringbuilder builder = new StringBuilder(classutils.getShortName(MethodParam.getParametertype()));文字列paramname = methodparam.getParametername(); if(paramname!= null){builder.append( ''); BUILDER.APPEND(PARAMNAME); }新しいhttpmediatypenotsupportedexception( "parameter(" + builder.tostring() + "):コンテンツタイプが見つかりません"); } list <mediatype> allsupportedmediatypes = new ArrayList <Mediatype>(); if(this.messageconverters!= null){for(httpmessageconverter:messageconverter:this.messageconverters){allsageconverter.getsupportedmediatypes()); if(messageconverter.canread(paramtype、contentType))){if(logger.isdebugenabled()){logger.debug( "reading [" + paramtype.getName() + "] as /" " + contentType +" /"を使用して[" + messagonverter + "]"); } return mesageConverter.read(paramtype、inputMessage); }}}新しいhttpmediatypenotsupportedexception(contentType、allsupportedmediatypes); } @ResponseBodyアノテーション:リクエストオブジェクトのヘッダー部分のAccept属性(コンマセラート)によると、1つずつ、処理できるHTTPMessageConverterを見つけます。
private void writewithmessageconverters(object returnvalue、httpinputmessage inputmessage、httpoutputmessage outputmessage)IoException、httpmediatypenotacepteception {list <mediatype> compatedmediatypes = inputmessage.geteders. if(AcceptedMediatypes.isempty()){AcceptedMediatypes = collections.singletonList(mediatype.all); } mediatype.sortbyqualityvalue(eccupedmediatypes);クラス<?リスト<Mediatype> allsupportedmediatypes = new ArrayList <Mediatype>(); if(getMessageConverters()!= null){for(mediatype AcceptedMediatype:AcceptedMediatypes){for(httpmessageconverter messageConverter:getmessageConverters()){if(messageconverter.canwrite(returnvalueetype) mesageconverter.write(returnValue、acceptedmediatype、outputmessage); if(logger.isdebugenabled()){mediatype contentType = outputmessage.getheaders()。getContentType(); if(contentType == null){contentType = AcceptedMediatype; } logger.debug( "wrond [" + returnValue + "] as /" " + contentType +" /"[" + mesageConverter + "]"); } this.responseargumentused = true;戻る; }}} for(httpmessageconverter mesageConverter:mesageconverter){allsuptortedmediatypes.addall(messageConverter.getSupportedMediatypes()); }} new httpmediatypenotacceptableException(allsupportedmediatypes); }JSONコンバーターをカスタマイズします
クラスcustomjsonhttpmessageconverterはhttpmessageconverter {// jacksonのjsonマッピングクラスプライベートオブジェクトマッパー= new objectMapper(); //このコンバーターのサポートタイプ:Application/JSONプライベートリストサポートmediatypes = arrays.aslist(mediatype.application_json); / ***コンバーターが入力コンテンツをjavaタイプに変換できるかどうかを判断します* @param clazz javaタイプを変換する必要があります* @param mediatype mediatype* @return*/ @override public boolean canread(class clazz、mediatype mediatype) } for(mediatype supportedmediatype:getSupportedmediatypes()){if(supportedmediatype.includes(mediatype)){return true; }} falseを返します。 } / ***コンバーターがJavaタイプを指定された出力コンテンツに変換できるかどうかを判断します* @param Clazz変換する必要があるJavaタイプ*このリクエストのために@param mediatype mediatype* / @override publowean canwrite(クラスクレイズ、メディアタイプ= null | | mediatype.all.equals(mediatype)){return true; } for(mediatype supportedmediatype:getSupportedmediatypes()){if(supportedmediatype.includes(mediatype)){return true; }} falseを返します。 } / ** *このconverterでサポートされているmediatypeを取得 * @return * / @override public list getSupportedmediatypes(){return supportedmediatypes; } / ***リクエストコンテンツを読み取り、JSONをJavaオブジェクトに変換します* @param Clazz変換する必要があるJavaタイプ* @param inputmessageリクエストオブジェクト* @throws ioexception* @throws httpmessagenotreadableexception* / @override公開オブジェクト(クラスclazz、httpinputmeputmestmessage、httpinputmeputmestmessage httpmessagenotreadableException {return mapper.readValue(inputmessage.getBody()、clazz); } /** * Convert Java object to Json to return content* @param o Object that needs to be converted* @param contentType Return type* @param outputMessage Receipt object* @throws IOException * @throws HttpMessageNotWritableException */ @Override public void write(Object o, MediaType contentType, HttpOutputMessage outputMessage) throws ioException、httpmessagenotwritableException {mapper.writevalue(outputmessage.getBody()、o); }}Mappingjackson2httpmessageをカスタマイズします
MappingJackson2HTTPMESSAGECONVERTERの親クラスABSTTTPMESSAGECONVERTERのParent Classメソッドの書き込みメソッドから見ることができます。これは、メソッドがWrite -Internalメソッドを介して結果を返す出力ストリームにデータを書き込むため、メソッドをオーバーライドする必要があるだけです。
@beanpublic mappingjackson2httpmessageconverter mappingjackson2httpmessageconverter(){return new mappingjackson2httpmessageconverter(){// write -internal methodを書き直し、最初にオブジェクトを削除する前に、@Overridectectected void void vioid void voidtected voidtected voidtected voidtectedはoutputMessage)IOEXCEPTION、HTTPMESSAGENOTWRITALEXCEPTION {// JacksonのObjectMapperを使用してJSON String ObjectMapper Mapper = new ObjectMapper(); string json = mapper.writevalueasstring(object); logger.error(json); // string result = json + "暗号化!"; logger.error(result); // output outputmessage.getBody()。write(result.getBytes()); }};}その後、このカスタムコンバーターをSpringに設定する必要があります。ここでは、webmvcconfigurerでconfiguremessageconvertersメソッドを書き換えてカスタムコンバーターを追加します。
//カスタムconverterの追加@OverRidePublic void configuremessageconverters(list <httpmessageconverter <? super.configuremessageconverters(コンバーター);}
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。