[go] Encrypt the returned content using a custom Httpmessageconverter

Source: Internet
Author: User
Tags object object

One person in the tech group this morning asked, "how do I unify the returned Json in Spring MVC?" ”。

The first reaction of most people is through the method in Spring interceptor (interceptor) postHandler . This is not practical, because when the program runs to the method, it is before the page is rendered after the data is returned, so the output stream in Response is closed, and it is natural that the returned data cannot be Processed.

In fact, This problem can be done with a few lines of code, because Spring provides a very rich set of extended support, whether it's mentioned earlier or later Interceptor MethodArgumentResolver HttpMessageConverter .

In Spring MVC, the controller layer is often used @RequestBody and @ResponseBody , through these two annotations, you can use the Java object directly in the controller as the request parameters and return content, and the completion of this transition between the role HttpMessageConverter .

HttpMessageConverterThe interface provides 5 methods:

    • canRead: Determines whether the converter can convert the request content to a Java object
    • canWrite: Determines whether the converter can convert Java objects to return content
    • getSupportedMediaTypes: Get the type of mediatype supported by this converter
    • read: reads the request content and translates it into a Java object
    • write: Writes a Java object to the returned content after it is converted

      read write The parameters of the method and the HttpInputMessage object, respectively, represent the HttpOutputMessage request and response part of the Http communication, and the getBody corresponding input stream and output stream can be obtained by means of the Method.

      here, you customize a Json converter as an example by implementing the Interface:

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 66676869707172737475767778798081 Class Customjsonhttpmessageconverter implements Httpmessageconverter { //jackson Json mapping class private Objectmapper Mapper = new Objectmapper ();  //support type for this converter: application/jsonprivate List supportedmediatypes = arrays.aslist ( Mediatype.application_json)  /*** Determine if the converter can convert the input to a Java type * @param clazz the Java type to be converted * @param mediatype the request Mediat ype* @return */@Overridepublic Boolean canRead (Class clazz, mediatype Mediatype) {if (mediatype = = Null) {return true;} For (mediatype supportedmediatype:getsupportedmediatypes ()) {if (supportedmediatype.includes (MediaType)) {return true;}} Return false;}  /*** Determines whether the converter can convert the Java type to the specified output * @param clazz the type of Java to be converted * @param mediatype the mediatype* of the request @return */@Overridepub Lic Boolean canWrite (Class clazz, mediatype Mediatype) {if (mediatype = = NULL | | MediaType.ALL.equals (mediatype)) {return true;} For (mediatype supportedmediatype:getsupportedmediatypes ()) {if (supportedmediatype.includes (MediaType)) {return true;}} Return false;} /*** obtains the mediatype* @return the converter supports */@Overridepublic List getsupportedmediatypes () {return supportedmediatypes;}  /*** reads the contents of the request, converts the Json into a Java object * @param clazz the Java type to be converted * @param inputmessage Request Object * @return * @throws ioexceptio n @throws httpmessagenotreadableexception*/@Overridepublic Object read (Class clazz, httpinputmessage Inputmessage) Throws ioexception, httpmessagenotreadableexception {return mapper.readvalue (inputmessage.getbody (), clazz);}  /*** Convert a Java object to Json return content * @param o object to convert * @param contentType return type * @param outputmessage Receipt Object * @throws Ioexcepti on* @throws httpmessagenotwritableexception*/@Overridepublic void write (Object o, mediatype contentType, Httpoutputmessage Outputmessage) throws ioexception, httpmessagenotwritableexception {mapper.writevalue ( Outputmessage.getbody (), o);}}

A considerable number of converters are now available by default in Spring, respectively:

name function Read Support mediatype Write support mediatype
Bytearrayhttpmessageconverter Conversion of data to byte arrays \/\ Application/octet-stream
Stringhttpmessageconverter Conversion of data to String types text/\* Text/plain
Formhttpmessageconverter The conversion between form and Multivaluemap application/x-www-form-urlencoded application/x-www-form-urlencoded
Sourcehttpmessageconverter The conversion between data and Javax.xml.transform.Source Text/xml and Application/xml Text/xml and Application/xml
Marshallinghttpmessageconverter Transform XML data using Spring's Marshaller/unmarshaller Text/xml and Application/xml Text/xml and Application/xml
Mappingjackson2httpmessageconverter Convert Json data using Jackson's objectmapper Application/json Application/json
Mappingjackson2xmlhttpmessageconverter Convert XML data using Jackson's xmlmapper Application/xml Application/xml
Bufferedimagehttpmessageconverter The conversion between data and Java.awt.image.BufferedImage All types supported by the Java I/O API All types supported by the Java I/O API

Back to the initial requirements, since the Json content that is being returned is encrypted, it is definitely a MappingJackson2HttpMessageConverter modification, and only the method needs to be overridden write .

From MappingJackson2HttpMessageConverter the method in the parent class AbstractHttpMessageConverter write , It can be seen that the method writeInternal writes data through the method to the output stream that returns the result, so only the method needs to be overridden:

1234567891011121314151617181920 @Beanpublic mappingjackson2httpmessageconverter mappingjackson2httpmessageconverter () {return New Mappingjackson2httpmessageconverter () {///overrides The Writeinternal method to first encrypt @overrideprotected void writeinternal before returning content ( Object object,httpoutputmessage Outputmessage) throws Ioexception,httpmessagenotwritableexception {//using Jackson's Objectmapper convert the Java object to Json stringobjectmapper mapper = new Objectmapper (); String json = mapper.writevalueasstring (object); Logger.error (json);//encrypt String result = json + "encrypted!" "; Logger.error (result);//output outputmessage.getbody (). write (result.getbytes ());}};}

After that, you will also need to configure this custom converter into Spring, where you can add a WebMvcConfigurer custom converter by overriding the configureMessageConverters method:

123456 Add a custom converter @overridepublic void Configuremessageconverters (list> converters) {converters.add ( Mappingjackson2httpmessageconverter ()); super.configuremessageconverters (converters);}

Test It:

This simply completes the ability to encrypt the returned Content.

(original address: Http://www.scienjus.com/custom-http-message-converter/)

[go] Encrypt the returned content using a custom Httpmessageconverter

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.