A true lightweight WebService framework--using JAX-WS (JWS) to publish WebService

Source: Internet
Author: User

WebService has historically been highly valued, especially in the Java Camp, WebService framework and technology. Well-known xfile (new such as CXF), Axis1, Axis2 and so on.

and Sun is not far behind, from the early Jax-RPC to now mature, support RPC calls and messaging Jax-WS have been tested by the market, very mature, and using JAX-WS development WebService revenue is very large, it is lightweight.

  

The development of WebService using JAX-WS requires only a few simple steps: The write interface and the implementation = = Release and generate the client (test or use).

In the development phase, we do not need to import external jar packages, because these APIs are readily available. First, the interface is written (the interface only need to put the class as @webservice, the method to be exposed to the client as @webmethod can be, the rest, such as @webresult, @WebParam, etc. are not necessary, and the client and server communication RPC and message-oriented two kinds, Difference and configuration later):

 PackageService;Importjava.util.Date;ImportJavax.jws.WebMethod;ImportJavax.jws.WebParam;ImportJavax.jws.WebResult;ImportJavax.jws.WebService;Importjavax.jws.soap.SOAPBinding;/*** WebService interface as Test * *@authorjohness **/@WebService @soapbinding (style=SOAPBinding.Style.RPC) Public InterfaceSayhiservice {/*** WebService method for performing tests*/@WebMethodvoidSayhidefault (); /*** WebService method for executing the test (with reference) * *@paramname*/@WebMethodvoidSayhi (@WebParam (name = "Name") String name); /*** WebService method for executing the test (for TIME check) * *@paramclenttime Client Time *@return0 indicates a time check failure 1 indicates a validation success*/@WebMethod @WebResult (name= "valid")    intChecktime (@WebParam (name = "Clienttime")) Date clienttime);}

Then is the implementation class (annotated @webservice and its endpointinterface properties are necessary):

 PackageService.imp;ImportJava.text.SimpleDateFormat;Importjava.util.Date;ImportJavax.jws.WebService;Importjavax.jws.soap.SOAPBinding;Importservice. Sayhiservice;/*** WebService implementation class as Test * *@authorjohness **/@WebService (Endpointinterface= "service. Sayhiservice ") @SOAPBinding (style=SOAPBinding.Style.RPC) Public classSayhiserviceimpImplementsSayhiservice {@Override Public voidSayhidefault () {System.out.println ("Hi, johness!."); } @Override Public voidSayhi (String name) {System.out.println ("Hi," + name + "!"); } @Override Public intchecktime (Date clienttime) {//accurate to secondsString Dateserver =Newjava.sql.Date (System.currenttimemillis ()). ToString ()+ " "                +NewJava.sql.Time (System.currenttimemillis ()); String dateclient=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"). Format (clienttime); returnDateserver.equals (dateclient)? 1:0; }}

Then there is the release (usually in two ways):

Mode one (this method can only be used as debugging, there are the following bugs:

Jdk1.6u17? The following compiler does not support SOAP that publishes document in Endpoint.publish manner, and must be added in the service interface and implementation class @SOAPBinding (style = SOAPBinding.Style.RPC) "annotations;

Access restricted, it seems that only native access (should be bound to the publish URL, such as under the use of localhost can only be native access) ...) :

 package   Mian;  import   Javax.xml.ws.Endpoint;  import   service.imp.SayHiServiceImp;  public  class        Main { /**   * Release WebService * Simple  */ public static  void   main (string[] args) {endpoint.publish ( "Http://localhost:8080/testjws/servic    E/sayhi ", new   Sayhiserviceimp ()); }}

Mode two (Web server-based servlet mode):

In Tomcat, for example, first write the Sun-jaxws.xml file and put it under Web-inf:

<?XML version= "1.0" encoding= "UTF-8"?><Endpointsxmlns= "Http://java.sun.com/xml/ns/jax-ws/ri/runtime"version= "2.0">    <Endpointname= "Sayhiservice"Implementation= "Service.imp.SayHiServiceImpl"Url-pattern= "/service/sayhi" /></Endpoints>

Then change the Web. XML to add Listener and Servlets (Url-pattern to the same OH):

<?XML version= "1.0" encoding= "UTF-8"?><Web-appXmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xmlns= "Http://java.sun.com/xml/ns/javaee"Xmlns:web= "Http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"version= "2.5">        <Listener>          <Listener-class>Com.sun.xml.ws.transport.http.servlet.WSServletContextListener</Listener-class>    </Listener>    <servlet>        <Servlet-name>Sayhiservice</Servlet-name>          <Servlet-class>Com.sun.xml.ws.transport.http.servlet.WSServlet</Servlet-class>    </servlet>      <servlet-mapping>          <Servlet-name>Sayhiservice</Servlet-name>          <Url-pattern>/service/sayhi</Url-pattern>      </servlet-mapping>        <welcome-file-list>        <Welcome-file>Index.html</Welcome-file>        <Welcome-file>Index.htm</Welcome-file>        <Welcome-file>index.jsp</Welcome-file>    </welcome-file-list></Web-app>

Finally deployed to Tomcat, it is worth mentioning that you may need to add the following jar packages (because Tomcat does not):

            

Start Tomcat.

  

Service-side work is done, pay attention to two things.

Note: The project needs to use UTF-8 encoding (at least sun-jaxws.xml must be in UTF-8 format);

For MyEclipse built-in Tomcat, there may be no need to manually add the above jar packages, but should be added when deploying independently because they use different class-path;

Multiple interfaces of different paths should also use the same wsservlet;

It is best to add @soapbinding (style = SOAPBinding.Style.RPC) annotations.

After deployment, open the browser input URL: http://localhost:8080/testjws/service/sayHi?wsdl. You can see things and prove that the release is successful.

Attach the project Tree chart:

  

Finally, the client uses, because WebService is platform-and language-independent, XML-based, so we can write or build clients in different languages entirely.

There are generally three ways to use (in the case of the Java language):

One, use the JDK's own tool Wsimport to generate the client:

  

With the Wsimport tool generated by the JDK, I generated the client file into the desktop src file (-D) and reserved the source file (-keep), specifying the package name (-P).

Then we can use the generated file to invoke the method that the server exposes:

            

It is worth mentioning that the JDK you build using and your client's JRE need to be matched!

From the above directory structure we can find: each WebMethod of the server is parsed into a single class (if the entity is used, the entity will be parsed to the client, and the source code, so it is recommended to use the entity carefully).

  

(The diagram above is an old diagram, just to show that JAXWS is generating classes for each WebMethod)

Our service is generated by a proxy class to invoke the services, and then we'll look at the usage:

 Packagetest;Importjava.util.Date;ImportJava.util.GregorianCalendar;Importjavax.xml.datatype.DatatypeConfigurationException;Importjavax.xml.datatype.DatatypeFactory;ImportJavax.xml.datatype.XMLGregorianCalendar;ImportTestjws.client.SayHiService;ImportTestjws.client.SayHiServiceImpService; Public classMain { Public Static voidMain (string[] args)throwsdatatypeconfigurationexception {//Get ServiceSayhiservice Service =NewSayhiserviceimpservice (). Getsayhiserviceimpport (); //SayhiService.sayhidefault (); Service.sayhi ("Ahe"); //Checktime//This is mainly about the time and date of the XML transfer, the method is also slightly complexGregorianCalendar Calender =NewGregorianCalendar (); Calender.settime (NewDate (System.currenttimemillis ())); Xmlgregoriancalendar xmldate=datatypefactory.newinstance (). Newxmlgregoriancalendar (calender);    System.out.println (Service.checktime (xmldate)); }}

Look at the output of the server, whether we call success:

  

    

It worked!

For the method of checking time the client also received feedback:

        

Second, use a project such as MyEclipse (Eclipse for Jave ee) to create a web Service client

        

Then fill in the WSDL address and I won't post the next steps.

Three, write their own code-_-, in fact, this method has to say is the best.

A true lightweight WebService framework--using JAX-WS (JWS) to publish WebService

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.