WebService is introduced

First let’s talk about why we need to learn webService such a technology….

Problem a

If our website needs to provide a weather forecast such a requirement, then what should we do ?????

Weather forecast such a function is not a simple JS component can be realized, its data is dependent on database analysis, even need satellite detection.. Our personal construction station is impossible to make such a database.

So since we can’t do it ourselves, can we find someone else?? We search from the search engine, we can find a lot of websites that provide weather forecasts, but what it returns is a webpage, and what we only need is the corresponding data!

We’re probably wondering, can we just use the data it returns instead of the processed web page it returns?

The result is webService, which is deployed on a Web server and exposes an API that can be invoked through the Web. That is to say: when we want to get the weather forecast information, we can call the service written by others, we can call the result!

Question 2

But we write website mainstream has several platforms: Java,.NET, PHP and so on, so deployed in the Web server server is webserice how can let us different platforms can call it?

We know that platforms such as Java and.NET may have different basic data types and complex data types in their languages, so how can we achieve the call??

To quote a passage

When they write applications to query the database, have not thought about why the query results can be returned to the upper application, even argue that this is the database should be done, actually otherwise, this is the database via TCP/IP protocol in communication with another application as a result, the upper is what kind of application, is to use what language, The database itself does not know that it has received a protocol, which is the SQL92 query standard protocol.

Whether it is Java,.NET, PHP and other platforms, as long as the web development can be HTTP protocol to communicate, and the returned data if common, then we have learned such a technology [XML]

So webService is really HTTP +XML

Understanding webService

WebService, as the name implies, is a Web-based service. It uses the Web(HTTP) to receive and respond to certain requests from external systems. To achieve remote invocation.

We can call the Internet query weather information Web service, then it is embedded in our program (C/S or B/S program) to, when users see weather information from our branches, he will think we gave him a lot of information service, but in fact we do nothing, just a simple call the server on a piece of code.

Learning WebService you can publish your service (a piece of code) to the Internet for others to call, also can call other people’s machine published WebService, just like using their own code.


Review of the Socket

We learned about the Scoket connection in the Java Basic Network Programming section.

The Socket server


public class SocketSer {

    public static void main(String[] args) throws Exception {

        ServerSocket ss = new ServerSocket(6666);
        boolean flag = true;
        while (flag) {
            // Receive requests from clients
            System.out.println("Listen for client data :");
            Socket sc = ss.accept();
            InputStream is = sc.getInputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            len = is.read(buffer);
            String getData = new String(buffer, 0, len);
            System.out.println("Data obtained from client :" + getData);
            // Business process case conversion
            String outPutData = getData.toUpperCase();

            // Write data to the client
            OutputStream os = sc.getOutputStream();
            os.write(outPutData.getBytes("UTF-8"));

            // Release resourcesos.close(); is.close(); sc.close(); } ss.close(); }}Copy the code

Socket the end of the service


public class SocketClient {

    public static void main(String[] args) throws Exception {
        // Get the data entered by the user
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter data :");
        String inputData = input.nextLine();

        // Enable a Socket port
        Socket sc = new Socket("127.0.0.1".6666);
        OutputStream os = sc.getOutputStream();
        os.write(inputData.getBytes());

        // Get the data returned by the server
        InputStream is = sc.getInputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        len = is.read(buffer);
        String getData = new String(buffer, 0, len);
        System.out.println("Data obtained from server :" + getData);
        / / whether the flowis.close(); os.close(); sc.close(); }}Copy the code

When we enter data from the client, the server converts the data to uppercase

In fact, HTTP protocol is based on Socket encapsulation, we can also access it in the IE browser. We can also get the data!


Description of Scoket and HTTP

ISO seven layer model: physical layer, data link layer, network layer, transport layer, presentation layer, session layer, application layer

  • Socket access: The Socket belongs to the transport layer, which is the implementation of Tcp/ IP protocol, including Tcp/ UDP. It is the basis of all communication protocols. Http requires Socket support, based on Socket

  • Socket communication features:

    • If the port is enabled, the communication is long connection communication, which is easily blocked by the firewall. It can be realized through the heartbeat mechanism, and it is difficult to develop
    • The transmitted data is usually a string, which is not readable
    • Socket ports are not easy to promote
    • The performance is optimal compared with other communication protocols
  • Http protocol access: an application-layer protocol that encapsulates sockets

    • cross-platform
    • Not friendly enough to transfer data
    • For services provided by third-party applications, service interface problems are exposed:
  • ** Data encapsulation is not friendly: you can encapsulate data in XML **Copy the code
  • ** Want to provide web services (HTTP + XML) to third-party applications = Web Service**Copy the code

Webservice-related terms

  • Noun 1: XML.Extensible Markup Language– Extensible Markup Language
    • XML, used to transmit formatted data, is the foundation of Web services.
    • Namespace – Indicates the namespace.
    • XMLNS = “http://itcast.cn” uses the default namespace.
    • XMLNS :itcast= “http://itcast.cn” uses the namespace with the specified name.
  • Noun 2: WSDL –WebService Description Language– Web Service Description Language.
    • Specify in XML where the service is – address.
    • Explain in XML what methods the service provides – and how to invoke them.
  • Term 3:SOAP-Simple Object Access Protocol(Simple Object Access Protocol)
    • SOAP, as an XML-based protocol, is used to transfer data over a network.
    • SOAP = over HTTP +XML data.
    • SOAP is based on HTTP.
    • SOAP consists of the following:
      • Envelope – Required section. Appears as the root element of XML.
      • Headers – Optional.
      • Body – Required. In the body section, include the server method to execute. And the data sent to the server.

Quick start

First, let’s try calling a webService written by someone else: we visit www.webxml.com.cn/zh_cn/index…

Go inside

When we enter a number, it looks up our phone’s location:

What we need to do now is to make this service available to our own applications. How do we do that?

Access the WebService in HTTP-get mode


public void get(String mobileCode ,String userID ) throws Exception{
		URL url=new URL("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode="+mobileCode+
				"&userID="+userID);
		HttpURLConnection conn=(HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){ // Result code =200
			InputStream is=conn.getInputStream();
			// Memory stream,
			ByteArrayOutputStream boas=new ByteArrayOutputStream();
			byte[] buffer=new byte[1024];
			int len=-1;
			while((len=is.read(buffer))! = -1){
				boas.write(buffer, 0, len);
			}
			System.out.println("GET request data :"+boas.toString()); boas.close(); is.close(); }}Copy the code


Http-client framework POST request

Why use the HttpClient tool:

  • The original Socket is based on the transport layer. Now the WebService we want to access is based on HTTP and belongs to the application layer. Therefore, our Socket communication needs to use HttpClient to send HTTP requests, so that the format can match

The steps to use HttpClient are as follows:

  1. Create an instance of HttpClient
  2. Create an instance of some connection method, in this case GetMethod. The address to join is passed in the constructor of GetMethod
  3. Configure the parameters to be transmitted, and the message header information
  4. Execute the method instance created in step 2 by calling the execute method of the instance created in step 1
  5. Read the string by response
  6. Release the connection. Whether the execution method succeeds or not, the connection must be released

	//2.Post request: Using the HTTP-client framework to simulate the implementation of Http requests
	public void post(String mobileCode ,String userID) throws Exception{

/**HttpClient to access the network implementation steps: * 1. Prepare a request client: browser * 2. Prepare request methods: GET, POST * 3. Set parameter * 4 to be passed. Execute request * 5. Obtain result */
		HttpClient client=new HttpClient();
		PostMethod postMethod=new PostMethod("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo");
		//3. Set request parameters
		postMethod.setParameter("mobileCode", mobileCode);
		postMethod.setParameter("userID", userID);
		//4. Execute request, result code
		int code=client.executeMethod(postMethod);
		//5. Get the result
		String result=postMethod.getResponseBodyAsString();
		System.out.println("Result of Post request:"+result);
	}


	//2.Post request: Using the HTTP-client framework to simulate the implementation of Http requests
	public void soap(a) throws Exception{

		HttpClient client=new HttpClient();
		PostMethod postMethod=new PostMethod("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx");
		//3. Set request parameters
          postMethod.setRequestBody(new FileInputStream("c:/soap.xml"));
          // Modify the header of the request
          postMethod.setRequestHeader("Content-Type"."text/xml; charset=utf-8");
		//4. Execute request, result code
		int code=client.executeMethod(postMethod);
		System.out.println("Result code :"+code);
		//5. Get the result
		String result=postMethod.getResponseBodyAsString();
		System.out.println("Result of Post request:"+result);
	}

Copy the code

wsimport

We used GET mode or http-client framework to call the WebService. In fact, these two methods also have disadvantages

  • Troublesome to transfer parameters 【 GET way is written on the request address, POST way to encapsulate one by one 】
  • Parse the string according to the returned XML

If we can pass in the whole object and return friendlier results, we can just use webService as we normally call Java classes.

Java also provides a similar method to make the WebService into a Java class for us to call, since it is a Java class, so we use it very convenient!

Making a webservice a Java class that we can call is essentially Java generating a local proxy for us to access the webservice through the local proxy

Quick start

Wsimport is a Java native command that must be configured with environment variables and preferably JDK 1.7 or later

Note that the IDE should come with the same JDK version as wsimPort, otherwise it will not be used!!

  • Wsimport use:The wsimport command is followed by the URL path of the WSDLgrammarwsimport [opations] <wsdl_uri>
    • Wsdl_uri: Uniform resource identifier for WSDLCopy the code
    • D: Specifies the location of the file to be outputCopy the code
    • S: Indicates that the Java source code is parsed. By default, class bytecode is parsedCopy the code
    • P: specifies the output package nameCopy the code

First let’s back up the CMD path to the desktop:

The local proxy is then generated for the WSDL file

The local proxy is really just a bunch of bytecode files

Package the resulting bytecode file into a JAR, then we just need to import the JAR package in the project, can call!

grammar

Jar CVF test.jarCopy the code

Originally, I wanted to generate jar package for the local proxy class file, and then import into the IDEA environment, so directly call the line. But idea always reported can not find the corresponding class, find a long time also can not find, very annoying !!!! I considered the following scenarios

  • ** The generated class file JVM does not match the JVM environment under IDEA **
  • The idea cache is not valid
  • The generated local proxy package name cn is not acceptable.

Finally I still did not find a way, if know is what reason, trouble tell me in the comment…. So for this test import, I’m not only generating class bytecode files, I’m also generating.java files. I’ll just use a Java file to test it.

Generate a local proxy in the Zhongfucheng directory, along with the Java source code

So I copied the Java source code into my project and used it for testing


Parsing the WSDL

Some classmates may doubt, why can wsimport so severe, so a url will be http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?WSDL generates local broker, in fact, we see the WSDL file.

It is important to note that the local proxy only has its methods, classes, and does not resolve the concrete implementation. The actual operation is actually done by webService. The concept of agency becomes clearer.

Custom WebService service

We used wsimPort to generate a local proxy to invoke webService services in the previous chapter, but we can also publish WebServices in our own web applications

If we publish a WebService, then other people can call our own webService!

So how do we customize the WebService and publish it?

After JDK version 1.6, ** provides support for WebServices through the JAX-WS package **

  • This method uses annotations to declare a WebService
  • Publish the Webserive service using JDK endpoint.publish ()

Quick start

Write an entity:


public class Phone {
	private String name;// Operating system name
	private String owner;/ / owner
	private int total;// Market share
	public String getName(a) {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getOwner(a) {
		return owner;
	}
	public void setOwner(String owner) {
		this.owner = owner;
	}
	public int getTotal(a) {
		return total;
	}
	public void setTotal(int total) {
		this.total = total; }}Copy the code

Publish services, annotate WSDL files to make them more readable…


package cn.it.ws.d;

import cn.it.ws.model.Phone;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
/* * Mobile phone service class, which provides external services through WebService * 1. Declare: @webService * 2. Publish EndPoint */

@WebService (serviceName="PhoneManager".// Change the service name
   targetNamespace="http://dd.ws.it.cn") // Modify the namespace, default package name, set to reverse
// Declare that the business class provides webService. By default, only public modified methods are published as WebService
public class PhoneService {

/ * *@WebMethod(operationName="getMObileInfo"): Change the method name *@WebResult(name="phone") : Modify the returned parameter name *@WebParam(name="osName") : Change the input parameter name */

	@WebMethod(operationName="getMObileInfo")
	public @WebResult(name="phone") Phone getPhoneInfo(@WebParam(name="osName")String osName){
		Phone phone=new Phone();
		if(osName.endsWith("android")){
			phone.setName("android"); phone.setOwner("google"); phone.setTotal(80);
		}else if(osName.endsWith("ios")){
			phone.setName("ios"); phone.setOwner("apple"); phone.setTotal(15);
		}else{
			phone.setName("windows phone"); phone.setOwner("microsoft"); phone.setTotal(5);
		}
		return phone;
	}
	@WebMethod(exclude=true)// Exclude this method
	public void sayHello(String city){
		System.out.println("Hello."+city);
	}
	private void sayLuck(String city){
		System.out.println("Friend:"+city);
	}
	 void sayGoodBye(String city){
		System.out.println("Bye."+city);
	}
	protected void saySayalala(String city){
		 System.out.println("Goodbye!+city);
	 }
	
	public static void main(String[] args) {
		String address1="http://127.0.0.1:8888/ws/phoneService";
/ / String address2 = "http://127.0.0.1:8888/ws/phoneManager";
Address: address of the service * 2: implementor of the service */

		Endpoint.publish(address1, new PhoneService());
// Endpoint.publish(address2, new PhoneService());
		System.out.println("WSDL addresses."+address1+"? WSDL"); }}Copy the code
  1. Add the @WebService annotation to the class to represent publishing a WebService service
  2. Publish a webService through an EndPoint(EndPoint service). The Endpoint is also a class that the JDK provides for publishing services. Its Publish method takes two parameters, the local service address and the class that provides the service. It is in the javax.xml.ws.* package.
  3. Publish (String Address, Object Implementor) Static methods create and publish endpoints at a given address for the specified implementor Object
  4. When you annotate a class with @WebService, all non-static methods in the class are exposed
  5. If you want a method to be private, add @webMethod (exclude=true) to the method to prevent it from being public.
  6. If the @webService annotation is added to a class, the class must have at least one method that can be exposed, or it will fail to start. Protected, private, final, and static methods are not public

@WebService	// Add this annotation to represent a WebService
public class HelloWorld {
	// Non-static final private methods are published by default
	public String sayHi(String name) {
		return "hello" + name;
	}
	@WebMethod(exclude=true)
	public void exclude(a){
		// Methods excluded by annotations
	}
	protected void protected1(a){
		// Protected methods are not published by default
	}
	private void private1(a){
		// Private methods are not published by default
	}
	public static void static1(a){
		// Static methods are not published by default
	}
	public final void final1(a){
		// Final methods are not published by default}}Copy the code

The generated WebService can be accessed in a browser


The SOAP protocol

Currently, WebService protocols include SOAP1.1 and 1.2.

  • They have different namespaces.
    • Soap1.1 namespace:
      • XMLNS: soap = “http://schemas.xmlsoap.org/soap/envelope/”
    • Soap1.2 namespace:
      • XMLNS: soap = "http://www.w3.org/2003/05/soap-envelope"Copy the code
  • The header information of SOAP1.1 is different from SOAP1.2.
    • SOAP1.1 A SOAPAction request header exists.
    • SOAP1.2 does not have a SOAPAction request header.
  • WSDL generated based on SOAP1.1 is also different from WSDL generated based on SOAP1.2. I’ll focus on namespaces.
  • The two protocols also request differently in CXF.
    • 1.1 the content-type: text/xm; charset=UTF-8
    • 1.2 the content-type: application/soap + XML; charset=UTF-8

SOA, UDDI concepts

SOA

Service-oriented Architecture (Soa) : Service-oriented Architecture, which is an idea advocated by IBM as plug and play, and hopes to develop applications in the way of assembling computers

Composition:

  • Web-oriented services and Web-oriented components: WebService: hard disk, CPU, and memoryCopy the code
  • EnterPrise Service Bus (ESB). The main boardCopy the code

uddi

Universal Description (Discovery and Integration) provides unified Description, Discovery, and Integration

  • It is a directory service through which webServcie can be registered and published for unified invocation by third-party callers
  • Not too much.

Implements the WebService of the interface

The service side


import javax.jws.WebService;

/** Interface oriented WebService publishing mode ** */
@WebService
public interface JobService {
	public String getJob(a);
}



Copy the code



import javax.jws.WebService;

@WebService(endpointInterface="cn.it.ws.e.JobService")// Set the service endpoint interface to specify the external service interface
public class JobServiceImpl implements JobService {

	@Override
	public String getJob(a) {
		return "JEE r&d engineer | Android development engineer engineer | | database front-end engineer | | test engineer operations engineer";
	}
    public void say(a){
    	System.out.println("Good morning!); }}Copy the code

The client


import javax.xml.ws.Endpoint;

public class Test {

	public static void main(String[] args) {
		JobService jobService=new JobServiceImpl();
		String address="http://192.168.114.10:9999/ws/jobservice";
		Endpoint.publish(address, jobService);
		System.out.println("WSDL addresses."+address+"? WSDL"); }}Copy the code

The CXF framework

Apache CXF is an open source Services framework that helps you build and develop Services that support a variety of protocols, such as: SOAP, POST/HTTP, and RESTful HTTP CXF simplify services so that they naturally integrate seamlessly with Spring.

Introduction to CXF: SOA framework

  • * CXF is a combination of Celtrix (ESB framework) and XFire (WebServer ice) and is donated to ApacheCopy the code
  • * The core of CxF is org.apache.cxf.Bus, similar to Spring's ApplicationContextCopy the code
  • * CXF relies on Spring by defaultCopy the code
  • * If all jars in the Apache CXF distribution are placed in lib, JDK1.6 or higher must be required. Otherwise, jax-WS version inconsistency will be reportedCopy the code
  • * CXF has a built-in Jetty server, which is a servlet container, like TomcatCopy the code

CXF characteristics

  • Seamless connection with Spring and Servlet, CXF framework integrated Servlet container Jetty
  • Support annotations to publish webServices
  • A list of services that can display a webservice
  • Can add interceptors: input interceptor, output interceptor:
  • Input log interceptor, output log interceptor, and user permission authentication interceptor

CXF development

To use the CXF framework, import the JAR package first

  • Asm 3.3. The jar
  • Commons logging – 1.1.1. The jar
  • CXF – 2.4.2. Jar
  • Jetty continuation – 7.4.5. V20110725. Jar
  • Jetty HTTP – 7.4.5. V20110725. Jar
  • Jetty – IO – 7.4.5. V20110725. Jar
  • Jetty ws-security – 7.4.5. V20110725. Jar
  • Jetty – server – 7.4.5. V20110725. Jar
  • Jetty – util – 7.4.5. V20110725. Jar
  • Neethi – 3.0.1. Jar
  • Wsdl4j – 1.6.2. Jar
  • Xmlschema – core – 2.0. The jar

interface


		import javax.jws.WebParam;
		import javax.jws.WebResult;
		import javax.jws.WebService;

@WebService(serviceName="languageManager")
public interface LanguageService {
	public @WebResult(name="language")String getLanguage(@WebParam(name="position")int position);

}
Copy the code

Implementation:


package cn.it.ws.cxf.a;

import org.apache.cxf.frontend.ServerFactoryBean;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;

/** Development language ranking Description services ** *@authorJun Li May 17, 2015 */
public class LanguageServiceImpl implements LanguageService {
	/* (non-Javadoc) * @see cn.it.ws.cxf.a.LanguageService#getLanguage(int) */
	@Override
	public String getLanguage(int position){
		String language=null;
		switch (position) {
		case 1:
			language="java"; 
			break;
		case 2:
			language="C";
			break;
		case 3:
			language="Objective-C";
			break;  
		case 4:
			language="C#";
			break;

		default:
			break;
		}
		return language;
	}
	1. ServerFactoryBean * - You can publish webService without setting annotations. No annotations supported * - Addition of interceptors not supported * 2. JaxWsServerFactoryBean * - Annotations supported * - Interceptors can be added * 3. Webservice access flow: * 1. Check whether the WSDL of the local proxy description is the same as that of the service side, colloquially known as handshake * 2. Through SOAP protocol to achieve communication, using POST request, data encapsulated in XML to meet the SOAP protocol * 3. The returned data is also soap communication, encapsulated in XML that meets the SOAP specification *@paramargs public static void main(String[] args) { LanguageService languageService=new LanguageServiceImpl(); ServerFactoryBean bean=new ServerFactoryBean(); / / the Endpoint: address, bean implementation object. SetAddress (" http://192.168.114.10:9999/ws/cxf/languangeService "); bean.setServiceClass(LanguageService.class); SetServiceBean (languageService); // The implementation of the service bean bean.create(); / / create, publish webservice System. Out.println (" WSDL address: http://192.168.114.10:9999/ws/cxf/languangeService? WSDL"); } * /
	public static void main(String[] args) {
		LanguageService languageService=new LanguageServiceImpl();
		JaxWsServerFactoryBean bean=new JaxWsServerFactoryBean();
		//Endpoint: address, implementation object
		bean.setAddress("http://192.168.114.10:9999/ws/cxf/languangeService");
		bean.setServiceClass(LanguageService.class);// Provide webservcie business classes or interfaces externally
		bean.setServiceBean(languageService);// The implementation bean of the service
		// Add input interceptor: Enter an interceptor to display log information
		bean.getInInterceptors().add(new LoggingInInterceptor());
		// Add output interceptor: Outputs interceptors that display log information
		bean.getOutInterceptors().add(new LoggingOutInterceptor());
		
		bean.create();// Create and publish webService
		System.out.println("WSDL address: http://192.168.114.10:9999/ws/cxf/languangeService? WSDL"); }}Copy the code

CXF integrates with Spring

  • Buy a Web project
  • Buy a way to prepare all jar packages, and copy all jar packages from the CXF_HOME\lib project into the new project’s lib directory. It already contains the Sring3.0 JAR package and the Jetty server package can not be used. Because the Tomcat server we want to deploy is in
  • Anyway, CXF’s core servlet, CXFServlet, is configured in web.xml
  • Unconsciously this configuration file’s function class intercepts all requests to /ws/* similar to the Struts2 filter

Web.xml configuration file:


<?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"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
    <display-name>CXF_Server</display-name>
    <! Add CXF Servlet to handle webService request -->
    <servlet>
        <servlet-name>cxf</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
        <load-on-startup>0</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>cxf</servlet-name>
        <url-pattern>/ws/*</url-pattern>
    </servlet-mapping>
    <! -- Spring listener add -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
</web-app>
Copy the code

Entity:


public class Employee {
	private Integer  id;
	private String name;
	private Integer age;
	public Integer getId(a) {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName(a) {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge(a) {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age; }}Copy the code

Interface:



package cn.it.ws.cxf.b;

import java.util.List;

import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;

import cn.it.ws.cxf.bean.Employee;
@WebService(serviceName="EmployeeService")
public interface EmployeeManager {

	void add(@WebParam(name="employee")Employee employee);

	@WebResult(name="employees")List<Employee> query(a);

}
Copy the code

Interface implementation:


package cn.it.ws.cxf.b;

import java.util.ArrayList;
import java.util.List;

import cn.it.ws.cxf.bean.Employee;

/** Business implementation class for employee management *@authorJun Li May 17, 2015 */
public class EmployeeManagerImpl implements EmployeeManager {
	private List<Employee> employees=new ArrayList<>();
	@Override
	public void add(Employee employee){
		// Add to the collection
		employees.add(employee);
	}
	@Override
	public List<Employee> query(a){
		returnemployees; }}Copy the code

Spring configuration information:


<?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:p="http://www.springframework.org/schema/p"
        xmlns:jaxws="http://cxf.apache.org/jaxws"
        xsi:schemaLocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">


    <bean id="employeeManagerImpl" class="cn.it.ws.cxf.b.EmployeeManagerImpl"></bean>
    <! - to configure CXF address: http://192.168.114.10:8080/CXF_Server/ws/employeeManager: http://192.168.114.10:8080 + CXF_Server (project name) + ws path (filtering) + / employeeManager (custom) class of service: the implementation of the service categories: interceptors -- -- >
    <jaxws:server address="/employeeManager" serviceClass="cn.it.ws.cxf.b.EmployeeManager">
        <jaxws:serviceBean>
            <ref bean="employeeManagerImpl"/>
        </jaxws:serviceBean>
        <! Configure the input interceptor to display log information -->
        <jaxws:inInterceptors>
            <bean class="org.apache.cxf.interceptor.LoggingInInterceptor"></bean>
        </jaxws:inInterceptors>
        <jaxws:outInterceptors>
            <bean class="org.apache.cxf.interceptor.LoggingOutInterceptor"></bean>
        </jaxws:outInterceptors>
    </jaxws:server>


</beans>
Copy the code

IDEA Uses WebService

Our Intellij Idea is a very handy Java IDE, and of course it also supports WebService development. Very useful… Since there are so many tutorials available online, HERE are a few that I think are good:

www.biliyu.com/article/986…

Blog.csdn.net/u010323023/…

Blog.csdn.net/dreamfly88/…

Get the weather forecast

We now webService basic entry, now I want to do is to write their own website can get the weather forecast information, so I go to www.webxml.com.cn/zh_cn/index… Found a weather service

This is the address of the WSDL weather forecast: ws.webxml.com.cn/WebServices… , so we just need to parse the WSDL service

If we don’t want all the information, we can find the data we want on the service, that is:


conclusion

  • The reason for using WebServices is that we need services that we can’t write ourselves. For example, weather forecast, so webService technology appeared. Webservices enable us to access services published by others on the Web. All we have to do is call it and get the relevant data.
  • Socket is actually a TCP/IP protocol encapsulation, and we use HTTP protocol on the Internet. A WebService is also a Web application. It also supports HTTP, of course. But WebService needs to be usable by different languages, so it uses XML for transmission.
  • So it has its own protocol **:SOAP(Simple Object Access Protocol). SOAP is Http+XML**.
  • We can use http-get to access webService because it uses native sockets for access. It’s a little complicated. We can then access WebService with the help of the HTTP-Client framework. The HTTP-client framework is a bit simpler than the HTTP-GET approach. But it’s still not neat enough.
  • Finally, we can use Java’s native WsImport to implement the local proxy. This method translates the WebService into a Java class, which we use to access the WebService. Very useful.
  • We can write our own webService.Annotate the service class. We can publish our webService service class through the EndPoint service.
    • To make WDSL files more readable, annotate the corresponding parameter names.
    • You can also control whether a method is published or not
  • SOAP is essentially an HTTP protocol that uses XML for transport.
  • SOA: Service-oriented architecture. Plug and play. So the coupling is very low, so you just add it when you use it.
  • UDDI (Universal Description, Discovery and Integration) is actually a directory structure of WebServices, but we seldom publish WebServices to it
  • A WebService that implements an interface is nothing more than an abstraction of it on a class level.
  • The CXF framework can seamlessly connect to Spring without our own Endpoint. It can keep a log or something.
  • We can also use the WebService under Idea to get the local proxy and generate THE WSDL file in a graphical manner.

If the article has the wrong place welcome to correct, everybody exchanges with each other. Students who are used to reading technical articles on wechat and want to get more Java resources can follow the wechat public account :Java3y