Summary of HTTP interface service-side combined with policy mode implementation

Source: Internet
Author: User

In the project, we often use the interface to Http+xml, and not just one, there may be multiple HTTP interfaces that require real-time interaction. But the public part of the HTTP interface is the same, and only the message parsing and return messages for each interface are different, At this time considering the change and the non-change of the isolation, the use of policy mode, the public part of the code extraction isolated, each HTTP interface of the different processing logic alone, so it is also convenient for later modification and extension, It is convenient to modify the individual interface processing logic and add new HTTP interfaces to the project for use without modifying the previous design. The following is a simple policy pattern for receiving http+xml interfaces:

The foundation of the Project: SSH architecture

First, the Basereceivehttpintfaction base class is implemented, the real-time receiving message action and the return result message action are obtained: the specific parsing logic and obtaining the return message logic extraction is isolated:

/***〈 A Word function brief description 〉<br> *〈 function Details 〉http receive interface base class implementation of the parent class implementation as prototype is not a singleton * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation of Tfaction * *@authorLilin *@see[Related Classes/methods] (optional) *@since[Product/module version] (optional)*/@Controller @scope (value= "Prototype") Public Abstract classBasereceivehttpintfactionextendsbasicaction {/**     */    Private Static Final LongSerialversionuid = -4667071743433536439l; PrivateIhttpmessagehandle Httpmessagehandle; /*** Function Description: <br> *〈 function detailed description for subclass injection Parent Class Property * *@paramHttpmessagehandle *@see[Related Classes/methods] (optional) *@since[Product/module version] (optional)*/     Public voidSethttpmessagehandle (Ihttpmessagehandle httpmessagehandle) { This. Httpmessagehandle =Httpmessagehandle; }     PublicString dobusiness () {InputStream InputStream=NULL; Try{InputStream=Request.getinputstream (); } Catch(IOException E1) {Logger.error ("IOException:", E1); } logger.info ("@ @HttpClient Parse Receive message:"); Saxreader SB=NewSaxreader (); String Returnstr=NULL; Try{Document Document=Sb.read (InputStream);            Logger.info (Document.asxml ()); //Save message Informationmap<string, object> map =Httpmessagehandle.handlemessage (document); //Splice return MessageReturnstr =httpmessagehandle.getresponsemsg (map, document); Logger.info ("@@ 报文 parsing success!"); } Catch(documentexception e) {logger.info ("@ @HttpClient parsing message Error!", E); } logger.info ("@@ 返回 message:" +returnstr);        Writeresponse (returnstr, response); return NULL; }    /*** function Description: <br> *〈 Function Detailed description 〉* *@paramRespxml *@paramResponse *@throwsIOException *@see[Related Classes/methods] (optional) *@since[Product/module version] (optional)*/    Private voidWriteresponse (String respxml, httpservletresponse response) {OutputStream out=NULL; Try {            byte[] data = Respxml.getbytes ("UTF-8")); out=Response.getoutputstream ();        Out.write (data); } Catch(IOException e) {logger.error ("Write Response Error:", E); } finally {            if(Out! =NULL) {                Try{Out.flush ();                Out.close (); } Catch(IOException e) {logger.error ("IOException:", E); }            }        }    }}

Then: Define the Common interface ihttpmessagehandle that the subclass needs to inject, the interface defines the parsing method that needs to parse the message, and the method to get the return text:

/***〈 A word function brief 〉<br> *〈 function Description 〉* *@authorLilin *@see[Related Classes/methods] (optional) *@since[Product/module version] (optional)*/ Public InterfaceIhttpmessagehandle {/*** function Description: <br> *〈 function Detailed description processing received message information * *@paramDocument *@return     * @see[Related Classes/methods] (optional) *@since[Product/module version] (optional)*/Map<string, object>Handlemessage (document document); /*** function Description: <br> *〈 function description) Get the message that needs to be returned * *@paramMap *@paramDocument *@return     * @see[Related Classes/methods] (optional) *@since[Product/module version] (optional)*/String getresponsemsg (Map<string, object>map, document document);}

Then: realize the actual processing of message information class: Crmhttpmessagehandle real-time processing of the CRM system sent XML message information, real-time assembly needs to return message information:

/***〈 A word function brief 〉<br> *〈 function Description 〉* *@authorLilin *@see[Related Classes/methods] (optional) *@since[Product/module version] (optional)*/@Service Public classCrmhttpmessagehandleImplementsIhttpmessagehandle {PrivateLogger Logger = Logger.getlogger (crmhttpmessagehandle.class); @ResourcePrivateLowpricetaskservice Lowpricetaskservice; @Override PublicString getresponsemsg (map<string, object>map, document document) {Logger.info ("Crmhttp Get responsemsg:");        Printlogbyentry (map); Document Doc=documenthelper.createdocument (); //Mbfservice StitchingElement Mbfservice = documenthelper.createelement ("Mbfservice");        Doc.add (Mbfservice); Element OUTPUT1= Documenthelper.createelement ("OUTPUT1");        Mbfservice.add (OUTPUT1); //Mbfheader StitchingElement Mbfheader = documenthelper.createelement ("Mbfheader");        Output1.add (Mbfheader); Pricecommonservice.addelement (Mbfheader,"Servicecode", (String) map.get ("Servicecode")); Pricecommonservice.addelement (Mbfheader,"Operation", (String) map.get ("Operation")); Pricecommonservice.addelement (Mbfheader,"Appcode", (String) map.get ("Appcode")); Pricecommonservice.addelement (Mbfheader,"UID", (String) map.get ("UID")); //Serviceresponse StitchingElement serviceresponse = documenthelper.createelement ("Serviceresponse");        Mbfheader.add (Serviceresponse); Pricecommonservice.addelement (Serviceresponse,"Status",NULL); Pricecommonservice.addelement (Serviceresponse,"Code",NULL); Pricecommonservice.addelement (Serviceresponse,"Desc",NULL); //Mbfbody StitchingElement mbfbody = documenthelper.createelement ("Mbfbody");        Output1.add (Mbfbody); Pricecommonservice.addelement (Mbfbody,"Reflag", (String) map.get ("Reflag")); Pricecommonservice.addelement (Mbfbody,"ErrorMessage", (String) map.get ("ErrorMessage")); Logger.info ("Crmhttp Final responsemsg:" +doc.asxml ()); returnDoc.asxml (); } @Override PublicMap<string, object>Handlemessage (document document) {Logger.info ("Crmhttp Start handlemessage:"); Map<string, object> res =NewHashmap<string, object>(); Lowpricetask Task=NewLowpricetask (); Element Root=document.getrootelement (); Element outelement= Root.element ("INPUT1"); Element Mbfheader= Outelement.element ("Mbfheader"); String Servicecode= Mbfheader.elementtexttrim ("Servicecode"); Res.put ("Servicecode", Servicecode); Logger.info ("# # Servicecode:" +Servicecode); String Operation= Mbfheader.elementtexttrim ("Operation"); Res.put ("Operation", operation); Logger.info ("# # Operation:" +operation); String Appcode= Mbfheader.elementtexttrim ("Appcode"); Res.put ("Appcode", Appcode); Logger.info ("# # Appcode:" +Appcode); String uId= Mbfheader.elementtexttrim ("UId"); Res.put ("UId", uId); Logger.info ("# # UId:" +uId); //set the return value        if(! Stringutils.isempty (servicecode) &&!Stringutils.isempty (operation))            {task.setmsg (Document.asxml ()); Task.setscannum (0); Task.setscanresult (F);            Task.setstoretime (Dateutils.getdate2 ());            Lowpricetaskservice.savetask (Task); Res.put ("Reflag", "S"); Res.put ("ErrorMessage", "S"); Logger.info ("@ @HttpClient Save message Success!"); } Else{res.put ("Reflag", "E"); Res.put ("ErrorMessage", "Message header Problem"); }        returnRes; }

Finally: the implementation of the actual sub-class to receive message information action: Inherit the base class, real-time injection of the parent class interface implementation, ultimately provided to the client url:http://lilin.com/lilin-web/crmreceivehttpintfaction.do

/***〈 A word function brief 〉<br> *〈 function Description 〉* *@authorLilin *@see[Related Classes/methods] (optional) *@since[Product/module version] (optional)*/@Controller Public classCrmreceivehttpintfactionextendsbasereceivehttpintfaction {/**     */    Private Static Final LongSerialversionuid = -104341558961432099l; @ResourcePrivateIhttpmessagehandle Crmhttpmessagehandle; @PostConstruct Public voidInjecthttpmessagehandle () {Super. Sethttpmessagehandle (Crmhttpmessagehandle); }}

In this way, the simple Http+xml message + Strategy mode implementation, is completed. Later needs to expand the use of new interface interface, as long as only to achieve their own

1, receive sub-class < reference crmreceivehttpintfaction >

2, Message processing class:< reference crmhttpmessagehandle>

3, provide the final service party URL to the client call;

HTTP Interface Service party combined with policy mode implementation summary

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.