AXIS2 Web 服务教程
欢迎阅读 Apache Axis2 教程。最近,我试图将我的Apache Axis2技能从 1.3 升级到最新版本 1.5.4,但我找不到任何不言自明且涵盖最新版本的教程。因此,它构成了我关于 Axis2 Web 服务教程帖子的基础。
Apache Axis2 教程
谁应该使用本教程?
本教程适用于有兴趣使用 Apache Axis2 开发和部署 Web 服务的 Java 程序员。
先决条件
本教程的范围是使用 Axis2 创建 Web 服务,使用 Java 客户端程序调用 Web 服务,以及使用 Soap UI 工具测试 Web 服务。需要对 Java、Web 服务、XML、Ant 和应用服务器 (Tomcat) 有基本的了解才能轻松理解本教程。
使用的软件和工具
- Java 开发工具包 (JDK) 1.6.0(Tomcat 7 至少需要 JDK 1.6)
- Apache Ant 1.7.0(Axis2 要求最低版本 1.6.5)
- Apache Axis2 1.5.4(二进制分发版)
- Eclipse 3.6.1 IDE 用于项目开发(您也可以使用其他 IDE,例如 NetBeans)
- Apache Tomcat 7.0.8
- SoapUI 用于测试我们的网络服务。
- Mac OS X 10.6.4(我正在使用 Mac OS,但本教程也适用于其他操作系统,但在执行命令时可能需要进行一些更改)
系统设置
-
下载最新版本的Apache Tomcat。截至目前,最新版本是 7.0.8,我在本教程中使用的就是这个版本。它要求最低 Java 版本 1.6,因此请确保它已安装在您的系统中。如果您的系统中未安装 Java 6,您应该先从Java SE 下载中下载并安装它。下载 Tomcat Core zip(apache-tomcat-7.0.8.zip)并解压以将其安装在您的系统上。设置JAVA_HOME环境变量以启动和停止服务器。
-
从Apache Axis2 – Releases下载 Apache Axis2 1.5.4 Binary Distribution zip 。此步骤是创建将部署到 tomcat 的 axis2.war 以及获取要在项目中使用的 axis2 库所必需的。
-
将 Axis2 二进制分发版 zip 解压到任何方便的目录中。转到 axis2-1.5.4/webapp 目录并运行“ant create.war”命令以在 axis2-1.5.4/dist 目录中创建 axis2.war 部署。如果您尚未安装 Apache Ant,可以从Apache Ant – Binary Distributions下载并安装它。请注意,我在从 War Distribution 下载 axis2.war 时遇到了一些问题。后来,我发现 axis2 War Distribution 中缺少几个 jar。War Distribution 仅包含 58 个 jar,而 Binary Distribution 包含 63 个 jar。(我懒得找出缺少哪些 jar。)
$ ant create.war Buildfile: build.xml init: [mkdir] Created dir: /Users/pankaj/Downloads/axis2-1.5.4/dist/temp [copy] Copying 59 files to /Users/pankaj/Downloads/axis2-1.5.4/dist/temp prepare.repo: [copy] Copying 9 files to /Users/pankaj/Downloads/axis2-1.5.4/dist/temp/WEB-INF [mkdir] Created dir: /Users/pankaj/Downloads/axis2-1.5.4/dist/temp/WEB-INF/conf [copy] Copying 1 file to /Users/pankaj/Downloads/axis2-1.5.4/dist/temp/WEB-INF/conf create.war: [war] Building war: /Users/pankaj/Downloads/axis2-1.5.4/dist/axis2.war [delete] Deleting directory /Users/pankaj/Downloads/axis2-1.5.4/dist/temp BUILD SUCCESSFUL Total time: 2 seconds
-
Deploy the axis2.war in the tomcat application server by copying it in tomcat webapps directory. You may need to restart the server if it’s not supporting hot deployment.
-
Go to https://localhost:8080/axis2/ and click on Validate link. If the Happy Axis page is coming with GREEN color then it means that axis2 is successfully deployed. Our system setup is ready now and we can proceed for creating Axis2 web services.
Creating Axis2 Web Service
For creating Axis2 Web Service archive, we need following:
- A Java Project (Axis2WSImplementation) with a class that will be exposed as a web service. In my example, I am exposing two operations from MyService class. The first operation getData input is String and returns String whereas the second operation getObjectData input is MyBean java object and returns MyBean java object after some data manipulation. Note that MyBean class implements Serializable interface so that it can be transferred over the network.
- Ant build.xml file that will be used to create aar, wsdl and client side stub and callback handler classes.
- services.xml file that will be part of the axis2 archive. This file will be put in the META-INF folder of the axis2 archive.
The project structure will look like the below image. Don’t get confused with the content inside build folder. They will be created when we will execute the build.xml ant file.
Axis2 Web Service Project Explanation
MyService.java: Implementation class that will be exposed as Axis2 web service.
package com.journaldev.ws;
import com.journaldev.bean.MyBean;
public class MyService {
public String getData(String input) {
return "Hi" + input;
}
public MyBean getObjectData(MyBean myBean) {
String name = myBean.getName();
int id = myBean.getId();
myBean.setId(id + 100);
myBean.setName("Output: " + name);
return myBean;
}
}
MyBean.java: Java Bean class that is input and output of getObjectData operation in web service.
package com.journaldev.bean;
import java.io.Serializable;
public class MyBean implements Serializable {
private static final long serialVersionUID = -1129402159048345204L;
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
services.xml: Axis2 web service related parameters are part of this xml file. ServiceClass parameter specifies the class that will be exposed as web service. The other important parameters are targetNamespace and schemaNamespace. services.xml
<service name="MyService" scope="application" targetNamespace="https://journaldev.com/">
<description>
MyService
</description>
<messageReceivers>
<messageReceiver mep="https://www.w3.org/2004/08/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver" />
<messageReceiver mep="https://www.w3.org/2004/08/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />
</messageReceivers>
<schema schemaNamespace="https://journaldev.com/xsd"/>
<parameter name="ServiceClass">com.journaldev.ws.MyService</parameter>
</service>
build.xml: Ant build file for performing Axis2 tasks. There are three targets defined whose details are:
- generate.wsdl: This target generates the MyService.wsdl file in the build folder. Make sure that targetNamespace and schemaTargetNamespace is same as in service.xml file.
- generate.service: This target generates axis2 archive in the build folder. It includes the services.xml file in the archive and archive name is MyService.aar
- generate.client: This target generates the client side classes. Make sure you run this after executing generate.wsdl so the MyService.wsdl file is present in the build folder.
build.xml
<project name="AxisWSImplementation" basedir="." default="generate.service">
<property environment="env"/>
<property name="build.dir" value="build"/>
<path id="axis2.classpath">
<fileset dir="${basedir}/lib">
<include name="*.jar"/>
</fileset>
</path>
<target name="compile.service">
<mkdir dir="${build.dir}"/>
<mkdir dir="${build.dir}/classes"/>
<mkdir dir="${build.dir}/resources"/>
<!--First let's compile the classes-->
<javac debug="on"
fork="true"
destdir="${build.dir}/classes"
srcdir="${basedir}/src"
classpathref="axis2.classpath">
</javac>
</target>
<target name="generate.wsdl" depends="compile.service">
<taskdef name="java2wsdl"
classname="org.apache.ws.java2wsdl.Java2WSDLTask"
classpathref="axis2.classpath"/>
<java2wsdl className="com.journaldev.ws.MyService"
outputLocation="${build.dir}"
targetNamespace="https://journaldev.com/"
schemaTargetNamespace="https://journaldev.com/xsd">
<classpath>
<pathelement path="${axis2.classpath}"/>
<pathelement location="${build.dir}/classes"/>
</classpath>
</java2wsdl>
</target>
<target name="generate.service" depends="compile.service">
<copy toDir="${build.dir}/classes" failonerror="false">
<fileset dir="${basedir}/resources">
<include name="**/*.xml"/>
</fileset>
</copy>
<jar destfile="${build.dir}/MyService.aar">
<fileset excludes="**/Test.class" dir="${build.dir}/classes"/>
</jar>
</target>
<target name="generate.client" depends="compile.service">
<taskdef name="wsdl2java"
classname="org.apache.axis2.tool.ant.AntCodegenTask"
classpathref="axis2.classpath"/>
<wsdl2java
wsdlfilename="${build.dir}/MyService.wsdl"
output="${build.dir}/resources" />
</target>
<target name="clean">
<delete dir="${build.dir}"/>
</target>
</project>
Generating WSDL, Axis Archive and Stub Files
- Execute generate.wsdl ant target to generate MyService.wsdl file.
- Execute generate.service ant target to generate the MyService.aar file.
- Execute generate.client ant target to generate the Stub classes.
Axis2 Web Service Deployment
Copy the MyService.aar in ~apache-tomcat-7.0.8/webapps/axis2/WEB-INF/services directory. Axis2 supports hot deployment of services, so you don’t need to restart the server. Check your service deployment on ListServices page (https://localhost:8080/axis2/services/listServices). MyService should be listed there with two operations.
Axis2 Web Service Testing
After deploying the service, first of all we need to test it. Here I am using SoapUI that is one of the best tools for Web Service Testing. If you don’t have it, you can download it from their website and install it easily. Steps for Testing using SoapUI
- Create a new SoapUI project with Project Name MyServiceTest (you can give any name you want) and Initial WSDL/WADL https://localhost:8080/axis2/services/MyService?wsdl (You can get this URL from Axis2 List Services page after clicking on the MyService link.). Leave other options with default value and click on OK button to create the SoapUI testing project.
- Take any of the Soap Bindings and double click on the getData and getObjectData SOAP Requests.
- Provide some values for input in the request and submit it to the web service end point URL. You should get output from the service similar to the below image. It confirms that our web service is up and running.
Now we will proceed with the last task of invoking the web service using Axis2 stub classes.
Axis2 Web Service invocation using Stub Files
- Create a Java Project Axis2Client in Eclipse.
- Create lib folder and copy all the Axis2 jars from downloaded binary distribution lib folder. Add these jars to the build path of the project.
- Copy earlier generated MyServiceStub.java and MyServiceCallbackHandler.java in the project src with correct package structure. In my case I copied them in com.journaldev package. If you have to provide these classes to somebody else, I would strongly suggest creating a jar from them and then distributing it with others to avoid any modifications.
- Create the Axis2ClientUsingStubsFromAnt client class to invoke the web service operations. The project structure will look similar like below image.
Axis2ClientUsingStubsFromAnt Code
package com.journaldev.ws.client;
import java.rmi.RemoteException;
import com.journaldev.MyServiceStub;
import com.journaldev.MyServiceStub.GetData;
import com.journaldev.MyServiceStub.GetDataResponse;
import com.journaldev.MyServiceStub.GetObjectData;
import com.journaldev.MyServiceStub.GetObjectDataResponse;
import com.journaldev.MyServiceStub.MyBean;
/**
*
* @author Pankaj - www.journaldev.com This class will invoke Axis2 web service
* operations using Stub classes
*
*/
public class Axis2ClientUsingStubsFromAnt {
/**
* END_POINT is the web service endpoint
*/
private final static String END_POINT = "https://localhost:8080/axis2/services/MyService";
public static void main(String[] args) throws RemoteException {
System.out.println("START");
// Create the Stub Object by passing the Web Service Endpoint URL
MyServiceStub stub = new MyServiceStub(END_POINT);
// Creating an input object for the getData operation
GetData getDataInput = new GetData();
// Setting the input part in the getData input object
getDataInput.setInput("PANKAJ");
// invoking the getData operation
GetDataResponse getDataOutput = stub.getData(getDataInput);
// get_return method returns the web service output object. Here its
// String, so we can
// directly print the returned value
System.out.println("Output:" + getDataOutput.get_return());
// Creating input object for the getObjectData operation
GetObjectData getObjectDataInput = new GetObjectData();
MyBean myBean = new MyBean();
myBean.setId(1);
myBean.setName("KUMAR");
// Setting the input part in the getObjectData input object
getObjectDataInput.setMyBean(myBean);
// invoking the getObjectData operation
GetObjectDataResponse getObjectDataOutput = stub
.getObjectData(getObjectDataInput);
// Get the MyBean object from the response object
MyBean myBeanOutput = getObjectDataOutput.get_return();
// Print the myBeanOutput values to check that web service operations
// are getting invoked
System.out.println("ID:" + myBeanOutput.getId() + "NAME:"
+ myBeanOutput.getName());
System.out.println("DONE");
}
}
Execute the Axis2ClientUsingStubsFromAnt class to invoke the web service. Output of the above program is:
START
log4j:WARN No appenders could be found for logger (org.apache.axis2.description.AxisService).
log4j:WARN Please initialize the log4j system properly.
Output:HiPANKAJ
ID:101NAME:Output: KUMAR
DONE
If you find the tutorial helpful in understanding Axis2 and getting started with it, please share your thoughts in the comment section. And yeah, don’t forget to share it across with others. Your two clicks and 5 seconds time can help someone else to learn Axis2 easily.