Use the CXF and jersey frameworks for Java WebService programming _java

Source: Internet
Author: User
Tags jboss wsdl

The

CXF
CXF is implemented on a xfire basis.
1) First, or package problem, in http://cxf.apache.org/download.html here can be down to the latest version of the CXF, of course, I use the latest version. Then there's the nonsense, build the Web project and put it in the jar bag. And the jar pack we don't choose, a bunch of all put in.
We'll see that it contains the spring jar package, and later when we need to deploy CXF as a Web project, we need to use the spring configuration file, which is later.
or interface classes and implementation classes:

@WebService Public 
interface Ireaderservice {public 
  Reader getreader (@WebParam (name= "name") String name,@ Webparam (name= "password") String password); 
  Public list<reader> getreaders (); 
} 
@WebService (endpointinterface= "Com.cxf.servlet.IReaderService", Servicename= "Readerservice") Public 
class Readerservice implements ireaderservice{public 
  Reader getreader (@WebParam (name= "name") String name, @WebParam ( Name= "password") String password) {return 
    new Reader (Name,password); 
  } 
   
  Public list<reader> getreaders () { 
    list<reader> readerlist = new arraylist<reader> (); 
    Readerlist.add (New Reader ("Shun1", "123")); 
    Readerlist.add (New Reader ("shun2", "123")); 
    Return readerlist 
  } 
} 

These two classes, except for annotations, are the same as the webservice that were spoken yesterday. Here is not much to say, the interpretation of annotations, you can look at the Java EE documents. But it should be easy to understand by meaning.
Next is JavaBean, or the reader class:

public class reader{ 
  private static final long serialversionuid = 1L; 
  private String name; 
  private String password; 
   
  Public reader () {} public 
  reader (String name,string password) { 
    this.name = name; 
    This.password = password; 
  } 
  The Get/set method omits public 
  String toString () {return 
    "Name: +name+", Password: "+password; 
  } 
   
}" 

The above has been finished.
2 Do we want to be a Web project? No, no, no, CXF has a lightweight container service, which is equivalent to spring itself providing the IOC container. We can use it first to test our deployment success.
Directly to a test class:

public static void Main (string[] args) { 
    System.out.println (' Server is starting ... '); 
    Readerservice readerservice = new Readerservice (); 
    Endpoint.publish ("Http://localhost:8080/readerService", readerservice); 
    System.out.println ("Server is started ..."); 
  } 

It's so simple. Directly publish the address, and then specify the interface or class is OK. I use the class here, but as far as possible with the interface, after all, interface-oriented programming is really the face of the object of thought.
We start to see the results:

We see the boot is complete, and then start the browser to see if it's successful.
Directly in the browser input http://localhost:8080/readerService?wsdl, we can see:

It generates the WSDL file we need, which means our deployment is successful.
3 after the success of the deployment, we are going to call, and its invocation is quite simple, similar to Xfire, get the interface, and then the same as the local class to invoke the method.

public static void Main (string[] args) { 
    Jaxwsproxyfactorybean Factorybean = new Jaxwsproxyfactorybean (); 
    Factorybean.setserviceclass (ireaderservice.class); 
    Factorybean.setaddress ("Http://localhost:8080/readerService"); 
     
    Ireaderservice Readerservice = (ireaderservice) factorybean.create (); 
    Reader reader = Readerservice.getreader ("Shun", "123"); 
    System.out.println ("Reader:" +reader); 
  } 

Here is very simple, but also to get a factory class, and then directly set the interface and address and then create can get the corresponding interface, here, like Xfire, but also need to call the end of the interface to define the prototype, otherwise these calls will be impossible to say.
We run to get the results:

No problem, it's the same as the result we expected.

4) But in many cases, we do not want our webservice and our applications to separate two servers, but want them to be in the same container, Tomcat or JBoss or other, so that we have to deploy the WebService through the Web to our previous completion.
Note that we need to use the spring definition file here.
First Look at Web.xml:

<?xml version= "1.0" encoding= "UTF-8"?> <web-app xmlns: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_3_0.xsd" id= "Webapp_ ID "version=" 3.0 "> <context-param> <param-name>contextConfigLocation</param-name> &L t;param-value>web-inf/beans.xml</param-value> </context-param> <listener> <listener -class>org.springframework.web.context.contextloaderlistener</listener-class> </listener> <ser Vlet> <servlet-name>CXFServlet</servlet-name> &LT;SERVLET-CLASS&GT;ORG.APACHE.CXF.TRANSPORT.SERVL Et. cxfservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>cxfservlet</se Rvlet-name> <url-pattern>/webseRvice/*</url-pattern> </servlet-mapping> </web-app> 
 

This is simple, just specifying the spring listener and the corresponding profile path, and specifying the CXF blocking method.
Next look at Beans.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:jaxws= "Http://cxf.apache.org/jaxws" 
  xsi:schemalocation= " 
    Http://www.springframework.org/schema/beans 
    Http://www.springframework.org/schema /beans/spring-beans.xsd 
    http://cxf.apache.org/jaxws 
    http://cxf.apache.org/schemas/jaxws.xsd "> 
  <import resource= "Classpath:meta-inf/cxf/cxf.xml"/> 
  <import resource= "classpath:meta-inf/cxf/" Cxf-extension-soap.xml "/> 
  <import resource= classpath:meta-inf/cxf/cxf-servlet.xml"/> 
   
  < Jaxws:endpoint id= "ReaderServicce2" implementor= "Com.cxf.servlet.ReaderService" address= "/readerservice2" 
    / > 
</beans> 

It's very simple here, just through Jaxws:endpoint defines a webservice,implementor is a WebService processing class, and address is its access path, similar to the Readerservice we wrote earlier.
We can then deploy it to Tomcat, which can be accessed directly via HTTP://LOCALHOST:8080/CXFWEBSERVICE/WEBSERVICE/READERSERVICE2?WSDL.

Some friends ask why the URL of this visit is different from the one in front of it. In fact, the previous access address is our own definition, and here the WebService address is configured in the configuration file, and is deployed through the Web project, where we need to use the project name, And we have configured the Url-pattern in Cxfservlet is WebService, so the final URL is consistent with the above.
We can see the effect:

This proves our deployment was successful.

You can test it again with the previous Test class, and note that you need to change the address to the URL after our release.
CXF compared to Xfire and more concise, although it added some annotations, but these innocuous, it is only the information in the previous services.xml in the class, but more convenient maintenance, but this is still a matter of opinion, some people like the configuration file, and some people do not like. In addition, CXF's calling method is more concise, compared to xfire its code is smaller, is a great progress.

Some friends in the process of building up a number of problems, without a reply, here to release code, there is a need to download a friend to see.
All packages under the Lib directory are not put in, and all the packages in the CXF can be placed.
Note: The IDE is idea, file structure is not common with eclipse, if you need to use under Eclipse, you can copy code and files directly to Eclipse's new project.

Jersey
Let's take a look at its basic usage.
Take a look at the project directly. Before you start the project, you should download the package yourself: https://maven.java.net/content/repositories/releases/com/sun/jersey/to run the example needs to download both server and client. Of course not to look so much, you can directly down this zip package, https://maven.java.net/service/local/artifact/maven/redirect?r=releases&g= Com.sun.jersey&a=jersey-archive&v=1.10&e=zip
1) directly to a JavaBean

@XmlRootElement public 
class Reader implements serializable{ 
  private static final long Serialversionuid = 1l;
   private String name; 
  private String password; 
   
  Public reader () {} public 
  reader (String name,string password) { 
    this.name = name; 
    This.password = password; 
  } 
  Omit Get/set method Public 
  String toString () {return 
    "Name: +name+", Password: "+password; 
  } 
}" 

Here is a label used to indicate the type of time it returns, that is, this reader class can be used for XML returns.
2 to a service class, then no longer like the previous cxf and xfire like to interface, directly to a class on the OK.

@Path ("/readerservice/{name}/{password}") Public 
class Readerservice { 
   
  @GET 
  @Produces ( Mediatype.application_json) Public 
  Reader Getreader (@PathParam ("name") String name, @PathParam ("password") String password) {return 
    new Reader (Name,password); 
  } 
   
  public static void Main (string[] args) throws IllegalArgumentException, IOException, urisyntaxexception { 
    Httpserver Server = httpserverfactory.create ("http://localhost:8080/"); 
    Server.start (); 
  } 
 

At this time to use a few tags, path believe that the Springmvc friend should know this way of writing, is URL matching, if not clear, you can go to see first. A Get label indicates that this method can only be accessed through a gets method, while produces represents the resulting result, which means that the system will close the reader object to a JSON result and return it.
It doesn't matter if you don't understand, it's understandable to wait and see the results.
And then there is a main method, I believe there are big questions. This is a lightweight internal container provided within the jersey, which can be used temporarily for debugging purposes, but it certainly can't be used for real use.
3) We write a test class

public class Readerclient {public 
 
  static void Main (string[] args) { 
    Client client = Client.create (); 
    WebResource resource = Client.resource ("http://localhost:8080/readerService/shun/123213"); 
    Reader reader = resource.get (reader.class); 
    SYSTEM.OUT.PRINTLN (reader); 
  } 
 
} 

Very simple code, should all understand, a client object, request WebService, return a resource, and then resource directly call the corresponding method, of course, this method is through our URL to match.

Here we first test it with a lightweight service. Run Readerservice directly, it contains a main method, run after we run readerclient, we can see the result is:

The results are correct.

We certainly don't want to use our own lightweight service as my server, we need to put it on the same server as our project, such as Tomcat,jboss.
4 Web Projects Of course, there is no web.xml.

 <?xml version= "1.0" encoding= "UTF-8"?> <web-app "xmlns:xsi=" /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_3_0.xsd "id=" webapp_id "version=" 3.0 "> <servlet> <servlet-name>jersey Web application< ;/servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.servletcontainer</servlet-class > <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet -name>jersey Web application</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-m apping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list& 
Gt </web-app> 

This specifies that all of the rest paths will be intercepted by Jersey.
We deploy to Tomcat to start and then rerun Readerclient, note to first modify the resource path:

WebResource resource = Client.resource ("http://localhost:8080/jerseyWebService/rest/readerService/shun/123213"); 

My project name is Jerseywebservice, please modify it according to your project name.
After the modification, we rerun the results as follows:

Consistent with the results above, the effect of deployment is the same and correct.

Related Article

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.