웹사이트 검색

AXIS2 웹 서비스 튜토리얼


Apache Axis2 튜토리얼에 오신 것을 환영합니다. 최근에 저는 Apache Axis2 기술을 1.3에서 최신 버전 1.5.4로 업그레이드하려고 시도했지만 최신 릴리스를 다루는 자명한 자습서를 찾을 수 없었습니다. 그래서 그것은 Axis2 Web Services Tutorial에 대한 나의 포스트의 기초를 이룬다.

Apache Axis2 튜토리얼

누가 이 자습서를 사용해야 합니까?

이 튜토리얼은 Apache Axis2를 사용하여 웹 서비스를 개발하고 배포하는 데 관심이 있는 Java 프로그래머를 대상으로 합니다.

전제 조건

이 튜토리얼의 범위는 Axis2를 사용하여 웹 서비스를 생성하고 Java 클라이언트 프로그램을 사용하여 웹 서비스를 호출하고 Soap UI 도구를 사용하여 웹 서비스를 테스트하는 것입니다. 자습서를 쉽게 이해하려면 Java, 웹 서비스, XML, Ant 및 응용 프로그램 서버(Tomcat)에 대한 기본적인 이해가 필요합니다.

사용된 소프트웨어 및 도구

  1. JDK(Java Development Kit) 1.6.0(Tomcat 7에는 최소 JDK 1.6 필요)
  2. Apache Ant 1.7.0(Axis2에는 최소 버전 1.6.5 필요)
  3. Apache Axis2 1.5.4(바이너리 배포)
  4. 프로젝트 개발용 Eclipse 3.6.1 IDE(NetBeans와 같은 다른 IDE도 사용할 수 있음)
  5. 아파치 톰캣 7.0.8
  6. 웹 서비스를 테스트하기 위한 SoapUI.
  7. Mac OS X 10.6.4(저는 Mac OS에서 작업하고 있지만 자습서는 다른 운영 체제에서도 작동해야 하지만 명령을 실행하는 데 약간의 변경이 필요할 수 있습니다.)

시스템 설치

  1. Download the latest version of Java SE Downloads. Download the Tomcat Core zip (apache-tomcat-7.0.8.zip) and unzip it to install it on your system. Set the JAVA_HOME environment variable to start and stop the server.

  2. Download Apache Axis2 1.5.4 Binary Distribution zip from Apache Axis2 – Releases. This step is required to create axis2.war that will be deployed to tomcat and to get the axis2 libraries to be used in projects.

  3. Unzip the Axis2 binary distribution zip into any convenient directory. Go to axis2-1.5.4/webapp directory and run the “ant create.war” command to create the axis2.war deployment in the axis2-1.5.4/dist directory. If you don’t have Apache Ant installed, you can download and install it from Apache Ant – Binary Distributions. Please note that I was facing some issue with axis2.war downloaded from War Distribution. Later on, I found out that few jars are missing in the axis2 War Distribution. War Distribution contains only 58 jars whereas Binary Distribution contains 63 jars. (I am feeling lazy to find out, which jars are missing.)

    $ 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
    
  4. 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.

  5. 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.

Axis2 웹 서비스 생성

Axis2 웹 서비스 아카이브를 생성하려면 다음이 필요합니다.

  1. 웹 서비스로 노출될 클래스가 있는 Java 프로젝트(Axis2WSImplementation). 내 예에서는 MyService 클래스에서 두 가지 작업을 노출하고 있습니다. 첫 번째 작업 getData 입력은 문자열이고 String을 반환하는 반면 두 번째 작업 getObjectData 입력은 MyBean 자바 객체이고 일부 데이터 조작 후 MyBean 자바 객체를 반환합니다. MyBean 클래스는 네트워크를 통해 전송할 수 있도록 Serializable 인터페이스를 구현합니다.
  2. Aar, wsdl 및 클라이언트 측 스텁과 콜백 핸들러 클래스를 생성하는 데 사용될 Ant build.xml 파일
  3. axis2 아카이브의 일부가 될 services.xml 파일. 이 파일은 axis2 아카이브의 META-INF 폴더에 저장됩니다.

Axis2 웹 서비스 프로젝트 설명

MyService.java: Axis2 웹 서비스로 노출될 구현 클래스.

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: 웹 서비스에서 getObjectData 연산의 입출력인 Java Bean 클래스.

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 웹 서비스 관련 매개변수는 이 xml 파일의 일부입니다. ServiceClass 매개변수는 웹 서비스로 노출될 클래스를 지정합니다. 다른 중요한 매개변수는 targetNamespaceschemaNamespace입니다. 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: Axis2 태스크를 수행하기 위한 Ant 빌드 파일. 세 가지 대상이 정의되어 있으며 세부 정보는 다음과 같습니다.

  1. generate.wsdl: 이 대상은 빌드 폴더에 MyService.wsdl 파일을 생성합니다. targetNamespace와 schemaTargetNamespace가 service.xml 파일과 동일한지 확인하십시오.
  2. generate.service: 이 대상은 build 폴더에 axis2 아카이브를 생성합니다. 아카이브에 services.xml 파일이 포함되며 아카이브 이름은 MyService.aar입니다.
  3. generate.client: 이 대상은 클라이언트측 클래스를 생성합니다. MyService.wsdl 파일이 빌드 폴더에 있도록 generate.wsdl을 실행한 후 이를 실행해야 합니다.

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>

WSDL, Axis 아카이브 및 스텁 파일 생성

  • generate.wsdl ant target을 실행하여 MyService.wsdl 파일을 생성합니다.
  • generate.service ant target을 실행하여 MyService.aar 파일을 생성합니다.
  • generate.client ant target을 실행하여 스텁 클래스를 생성합니다.

Axis2 웹 서비스 배포

Axis2 웹 서비스 테스트

서비스를 배포한 후 먼저 테스트해야 합니다. 여기서는 웹 서비스 테스트를 위한 최고의 도구 중 하나인 SoapUI를 사용하고 있습니다. 없는 경우 해당 웹 사이트에서 다운로드하여 쉽게 설치할 수 있습니다. SoapUI를 사용한 테스트 단계

  1. 프로젝트 이름 MyServiceTest(원하는 이름을 지정할 수 있음) 및 초기 WSDL/WADL https://localhost:8080/axis2/services/MyService?wsdl(Axis2 목록에서 이 URL을 얻을 수 있음)로 새 SoapUI 프로젝트를 만듭니다. MyService 링크를 클릭한 후 서비스 페이지.). 다른 옵션은 기본값으로 두고 확인 버튼을 클릭하여 SoapUI 테스트 프로젝트를 만듭니다.
  2. 비누 바인딩 중 하나를 선택하고 getData 및 getObjectData SOAP 요청을 두 번 클릭합니다.
  3. 요청에 입력할 일부 값을 제공하고 웹 서비스 끝점 URL에 제출합니다. 아래 이미지와 유사한 서비스 출력이 표시되어야 합니다. 웹 서비스가 실행 중임을 확인합니다.

스텁 파일을 사용한 Axis2 웹 서비스 호출

  1. Eclipse에서 Java 프로젝트 Axis2Client를 생성합니다.
  2. lib 폴더를 만들고 다운로드한 바이너리 배포 lib 폴더에서 모든 Axis2 jar를 복사합니다. 이 jar 파일을 프로젝트의 빌드 경로에 추가합니다.
  3. 이전에 생성된 MyServiceStub.javaMyServiceCallbackHandler.java를 올바른 패키지 구조로 프로젝트 src에 복사합니다. 제 경우에는 com.journaldev 패키지에 복사했습니다. 이러한 클래스를 다른 사람에게 제공해야 하는 경우 수정을 방지하기 위해 해당 클래스에서 jar을 만든 다음 다른 사람에게 배포하는 것이 좋습니다.
  4. Axis2ClientUsingStubsFromAnt 클라이언트 클래스를 생성하여 웹 서비스 작업을 호출합니다. 프로젝트 구조는 아래 이미지와 유사합니다.

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");

	}

}

Axis2ClientUsingStubsFromAnt 클래스를 실행하여 웹 서비스를 호출합니다. 위 프로그램의 출력은 다음과 같습니다.

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

튜토리얼이 Axis2를 이해하고 시작하는 데 도움이 된다면 의견 섹션에서 의견을 공유하십시오. 그리고 예, 다른 사람들과 공유하는 것을 잊지 마십시오. 두 번의 클릭과 5초의 시간으로 다른 사람이 Axis2를 쉽게 배울 수 있습니다. :)