WebService Case Introduction (Basic article)

Source: Internet
Author: User
Tags gettext soap webservice annotation node server wsdl

[Copyright: The author of this article is original, reproduced please indicate the source]
Article Source: http://blog.csdn.net/sdksdk0/article/details/52106690
Juppé id:sdksdk0 Email: [Email protected]

First, Introduction

Webservice: Cross-language cross-platform remote invocation technology. Web service is Web services, which is a cross-platform remote invocation technology that is a remote invocation technology across programming languages and cross-operating system platforms.
JAVA has three kinds of webservice specifications, namely Jax-WS (JAX-RPC), Jaxm&saaj, Jax-rs.
WebService three elements: SOAP, WSDL, UDDI

JAX-WS is all called Java API for xml-based WebServices, the early SOAP-based Java Web Services specification JAX-RPC (Java API for Xml-remote Procedure call).
The JAXM (JAVA API for XML message) primarily defines the Api,saaj that is required to send and receive messages (soap with Attachment APIs for JAVA,JSR 67) is an API that is used in conjunction with JAXM to build SOAP Package and parse SOAP packages provide important support, support for attachment transfer, and so on.
Jax-rs is a set of Web service specifications developed by Java for the representation state Transfer style.

Second, the application scenario

In the enterprise as a whole informatization, the enterprise generally more or less exist in some existing systems, these various systems can not be all overturned, re-planning and development, because many suppliers in a certain field also do a very professional, Bo Zhong family and integration should be a more realistic and desirable practice. Integration across systems through webservice not only shortens the development cycle, reduces risk, reduces code complexity, and enhances application maintainability because WebService supports cross-platform and adheres to standard protocol (SOAP).

The function of a software is exposed in webservice way to achieve software reuse. For example, the forecast of the above analysis, the weather query function is exposed to WebService interface is very easy to integrate in other systems; another example of a third-party logistics system will express inquiries, express registration exposed, thus integrated in the e-commerce system.

Third, the SOAP protocol

SOAP is a network communication protocol
Soap Simple Object Access Protocol
SOAP is used for communication between cross-platform applications
SOAP is designed to communicate over the Internet (HTTP)
SOAP = Http+xml, which is actually sending XML data over HTTP
SOAP is simple and extensible to support object-oriented
SOAP allows you to cross firewalls

The socket is the basis of all communication and is irrelevant to the language of the platform.
The socket uses the TCP protocol for high transmission efficiency. It is suitable for high concurrency scenarios of large data, high concurrency requires multithreading and is used to the thread pool, coding is complex. Sockt High-concurrency framework Mina.
The socket is just a stream transfer, and the format of the transmission needs to be defined by the programmer.

WebService is using the SOAP protocol, and the SOAP protocol is based on the application layer protocol of the HTTP protocol, which is essentially http+xml. The SOAP protocol is a standard and low transmission efficiency. The use of transport data is not too large, but also supports high concurrency, limited by the Web container. Both the SOAP protocol and the WSDL support are international standards and do not require a custom data format, only object-oriented development.

Iv. WSDL

WebService's instruction manual. Describes the service address of the WebService and the WebService service interface, parameters, and return values.
Reading method: read from bottom to top.

    1. Find the Service node first: In each WSDL, there is only one service node. Also called the Service View node. There are port node server ports in the service.
    2. Find the binding node based on the binding property of the port node. Find the PortType node based on the Type property of the binding node.
    3. The porttype node is the type of interface that we define for the SEI service. The Operation node in Prottype is the method name.
    4. The input of the operation node is the definition of the parameter, and output is the definition of the return value.
    5. Input has a property called the Message,message property corresponding to the message node. There is an element that corresponds to the element node.
    6. The element node is defined in the XSD. Defines the type of data. Both the parameter and the return value are defined therein.
V. Weather Enquiry System (Basic)

Here, the basic concepts of webservice have been understood, then start our happy coding steps! In this case we need to create a new two Java project, one for the server, one for the client. Source code can be downloaded through the link at the end of the article.

5.1 Service Side

1. Write an SEI, which is an interface

publicinterface WeatherInterface {        String queryWeather(String cityName);    }

2, write an SEI implementation class, need to implement the SEI interface, but also need to add a @webservice annotation on this implementation class

    @Webservice    publicclass WeatherInterfaceImpl implements WeatherInterface {        publicqueryWeather(String cityName) {            System.out.println("接收到客户端发送的城市名称:"+cityName);              String result="晴,高温预警";            return result;        }    }

In this step, if you because of the WebService add comment system error, you can first follow the error notification first change to jase-1.5, and then go to build path to re-change back to your original java1.7 or 1.8.

3, publish the service. Use the endpoint static method publish.

    publicclass WeatherServer {        publicstaticvoidmain(String[] args) {            //发布服务            Endpoint.publish("http://127.0.0.1:11111/weather"new WeatherInterfaceImpl());        }    }

Access Address: Http://127.0.0.1:11111/weather

See porttype in HTTP://127.0.0.1:11111/WEATHER?WSDL.

Seeing the effect indicates that the boot was successful.

5.2 Client

For clients, we can generate client code using only Wsimport from Java.

Using Wsimport to generate the client calling code,
In the bin directory of the JDK's installation directory, there is a wsimport command.

The client calling code can be generated from the WSDL document.

Create a new Java project WebServiceClient, and then go to the SRC directory of the project and run the following command in the SRC directory via cmd: (note the space)

Wsimport-s. http://127.0.0.1:11111/weather?wsdl


After the build, we can call it directly:

1. Create a Service View object
2. Attempt to obtain porttype (SEI) object from service
3. Call the service-side method
4. Printing results

    publicclass WeatherClient {    publicstaticvoidmain(String[] args) {        WeatherInterfaceImplService  service=new WeatherInterfaceImplService();        WeatherInterfaceImpl portType=service.getWeatherInterfaceImplPort();        String result=portType.queryWeather("衡阳");        System.out.println(result);    }    }

Vi. Weather Enquiry (public network)

The method we have just used is our own definition, but often life, we need to constantly update the weather information, so this time we can call the public network to deal with, and the previous, we also need the server and the client.

6.1 Service Side

The server uses a third-party, and imports its already generated multiple classes, Cn.com.webxml. This can be downloaded directly from the source code I provide.

6.2 Client
 Public Static void Main(string[] args) {//Create a service view        //weatherwebservice service=new weatherwebservice ();URL url =NULL;Try{URL =NewURL ("Http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?WSDL"); }Catch(Malformedurlexception e)        {E.printstacktrace (); } QName Qname=NewQName ("http://WebXml.com.cn/","Weatherwebservice");        Service service=service.create (url,qname); Weatherwebservicesoap Porttype=service.getport (Weatherwebservicesoap.class);//service.getweatherwebservicesoap ();Arrayofstring Arrayofstring=porttype.getweatherbycityname ("Hengyang"); for(Stringstring: Arrayofstring.getstring ()) {System. out. println (string); }    }

VII. Regional Enquiry System

Create a regional query service system, publish WebService services for clients to call, and query the region information according to ParentID. The client passes XML-formatted data to the server, and the server responds to the client with XML-formatted data.

Reasons for passing XML data:

    • 1, cross-language may take a lot of time to debug, if the direct delivery of XML will save debugging time. Both the parameter and the return value are string types and are very simple.
    • 2, if the parameters change, you can not modify the interface, cannot regenerate the client code.
    • 3. Data in XML format is cross-platform.

Implementation steps

- 创建一个java工程。- 导入mysql数据库驱动及其相关的jar包。- 创建一个SEI。- 创建一个SEI实现类,调用dao查询区域列表。- 发布服务,使用Endpoint的publish方法发布服务。

Client:

    • Generating the client calling code
    • Create a service view
    • Get porttype from the service view
    • Invoking a service-side method
7.1 Service Side

1, create a new Area information interface, Areamodel. java
Private String Areaid;
Private String AreaName;
Private String ParentID;
Private String Arealevel;
Implement its Get\set method

2, a new Areadao.java, for access to the MySQL database in the region information, the database of SQL script has been put into the source code, readers can download themselves. is the ability to connect to a database.

 Public List<Areamodel>Queryarea (StringParentID, int start, int end) {Connection Connection= NULL; PreparedStatement pstmt= NULL;ResultSet ResultSet = NULL;List<Areamodel>Arealist= NewArrayList<>(); try {//Load Database driverClass.Forname ("Com.mysql.jdbc.Driver");//Get connectionConnection=DriverManager.Getconnection ("JDBC:MYSQL:///DAY15","ZP","a");StringSql="Select *from area where parentid=?" Limit?,? "; Pstmt=Connection.Preparestatement (SQL); Pstmt.SetString (1, ParentID); Pstmt.Setint (2, start-1); Pstmt.Setint (3, end-start-1);ResultSet=Pstmt.ExecuteQuery (); while(ResultSet.Next ()) {Areamodel model=NewAreamodel (); Model.Setareaid (ResultSet.GetString ("Areaid")); Model.Setareaname (ResultSet.GetString ("AreaName")); Model.Setarealevel (ResultSet.GetString ("Arealevel")); Model.Setparentid (ResultSet.GetString ("ParentID"));//Add to Zone listArealist.Add (model); }}catch (Exception e) {E.Printstacktrace (); }finally{try {ResultSet.Close (); } catch (SQLException e) {//TODO auto-generated catch blockE.Printstacktrace (); } try {pstmt.Close (); } catch (SQLException e) {//TODO auto-generated catch blockE.Printstacktrace (); } try {Connection.Close (); } catch (SQLException e) {//TODO auto-generated catch blockE.Printstacktrace (); }        }returnArealist; }

3. Write an area query sei

publicinterface AreaInterface {    String queryArea(String area);}

4. Implement the DAO method of Sei.

@WebService Public  class Areainterfaceimpl implements areainterface {    @Override     PublicStringQueryarea(String area) {//parsing XML query criteriaAreamodel model =NULL;Try{model = Parsexml (area); }Catch(Documentexception e)        {E.printstacktrace (); } Areadao dao=NewAreadao ();        List<areamodel> List=dao.queryarea (Model.getparentid (), Model.getstart (), Model.getend ()); String result =NULL;Try{result = List2xml (list); }Catch(Exception e) {//TODO auto-generated catch blockE.printstacktrace (); }returnResult }PrivateAreamodelParsexml(String XML)throwsdocumentexception{Document document=documenthelper.parsetext (XML); String Parentid=document.selectsinglenode ("/queryarea/parentid"). GetText (); String Start=document.selectsinglenode ("/queryarea/start"). GetText (); String End=document.selectsinglenode ("/queryarea/end"). GetText (); Areamodel model=NewAreamodel ();        Model.setparentid (ParentID);        Model.setstart (Integer.parseint (start)); Model.setend (Integer.parseint (end));returnModel }PrivateStringList2xml(list<areamodel> List)throwsException {Document document = Documenthelper.createdocument ();//Add to root nodeElement root = Document.addelement ("Areas"); for(Areamodel areamodel:list) {Element area = root.addelement ("Area"); Area.addelement ("Areaid"). SetText (Areamodel.getareaid ()); Area.addelement ("AreaName"). SetText (Areamodel.getareaname ()); Area.addelement ("Arealevel"). SetText (Areamodel.getarealevel ()); Area.addelement ("ParentID"). SetText (Areamodel.getparentid ()); }returnDocument.asxml (); }}

5. Publishing Service

publicclass AreaServer {    publicstaticvoidmain(String[] args) {        Endpoint.publish("http://127.0.0.1:11111/area"new AreaInterfaceImpl());    }}

Seeing this interface through browser access indicates that the operation was successful.

7.2 Client

In the same way as before, use Wsimport to generate the client code.
Run cmd in the SRC directory of the Java project.
Wsimport-s. http://127.0.0.1:11111/area?wsdl

After the build, it looks like this:

The client makes the call

 Public classareaclient { Public Static void Main(string[] args) {Areainterfaceimplservice service=NewAreainterfaceimplservice ();        Areainterfaceimpl Porttype=service.getareainterfaceimplport (); String Result=porttype.queryarea (Getqueryxml ("1.1.",1,Ten)); System. out. println (Result); }Private StaticStringGetqueryxml(String ParentID,intStartintEnd) {String xml="<?xml version=\" 1.1\ "encoding=\" utf-8\ "? >\n "+"<queryarea>\n"+"<parentid>"+parentid+"</parentid>\n"+"<start>"+start+"</start>\n"+"<end>"+end+"</end>\n"+"</queryarea>";returnxml }}

Output Result:

Summary: The content of this article about WebService is very very basic, the involved in some of the protocols or use of methods estimated that some people do not know, we need to expand their horizons, to learn more new things, the heart of some not very common things to resist, some friends will say "Well, you talk about these things are too basic, we in the actual project how to apply", some directly call the third-party URL and reference documents to take care of, in fact, is more convenient, then we use other people's things when there is no consideration of its underlying principle of implementation, deep into its marrow is really mastered, Otherwise, we are still the kind of people who will only replicate the paste and blindly call the various third-party APIs. Share! Next time will bring more practical CXF implementation JAX-WS. Welcome attention!

SOURCE Download:
https://github.com/sdksdk0/webweather-basedemo-
Https://github.com/sdksdk0/AreaWebService

WebService Case Introduction (Basic)

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.