Está en la página 1de 18

Axis2

I. Giới thiệu Axis2:


Axis2 là một web service framework, nó được thiết kể để thực hiện các công việc:
+ Gửi SOAP messages
+ Nhận và xử lý SOAP messages
+ Tạo web service bằng lớp POJO
+ Tạo lớp cài đặt cho cả server và client sử dụng WSDL
+ Dễ dàng rút trích WSDL của service…

Bạn có ứng dụng được thiết kế để gửi và nhận message. Ở tầng giữa, bạn có Axis2. Giả sử Axis đang chạy ở hai
phía client và server, tiến trình như sau:

+ Người gửi tạo SOAP message.


+ Axis handlers thực hiện các hành động cần thiết trên message như mã hóa (của WS-Security) thông tin có liên
quan.
+ Trình vận chuyển sẽ gửi message.
+ Phía bên nhận, trình transport listener phát hiện message.
+ Chuyển message đến handlers ở phía nhận.
+ Một khi message được xử lý trong pha "pre-dispatch", nó sẽ được đưa đến dispatcher, sau đó nó sẽ được chuyển
cho ứng dụng thích hợp.

Có hai phiên bản chính của Axis2:


+ Standard Binary Distribution: là phiên bản hoàn chỉnh của Axis, chứa sample và nhiều script hữu ích. Nó được
sử dụng để cài đặt như một server độc lập.
+ WAR (Web Archive) Distribution: là ứng dụng web của Axis2, được triển khai trên hầu hết các trình chứa
servlet.

Để phát triển các dịch vụ và ứng dụng, bạn sẽ cần bảng phân phối Standard Binary vì nó chứa tất cả file jar cần
thiết cũng như các script hữu ích để dễ dàng phát triển ứng dụng (axis2.bat, axis2.sh, axis2server.bat,
axis2server.sh, java2wsdl.bat, java2wsdl.sh, wsdl2java.bat, wsdl2java.sh, setenv.sh). Download hai phiên bản tại:
http://ws.apache.org/axis2/download/1_3/download.cgi

Cài Axis2 như một phần của trình chứa servlet tương thích J2EE:
+ Download http://apache.oregonstate.edu/ws/axis2/1_3/axis2-1.3-war.zip
+ Giải nén, bỏ file war vào webapps của Tomcat: C:\Program Files\Apache Software Foundation\Tomcat
6.0\webapps
+ http://127.0.0.1:8989/axis2/ (username/passwd là admin/axis2)
II .Ứng dụng mẫu:
+ Cấu trúc của ứng dụng
projectname
+ src
+ org.sample.service
+ BusinessService
+ test
+ org.sample.service
+ BusinessTest
+ resources
+ META-INF
+ services.xml
build.xml

+ Tạo lớp service:


BusinessService.java
package org.sample.service;

public class BusinessService {

public Float calShippingCode(Integer zip, Float weight) {


return new Float(zip.intValue() * weight.floatValue());
}
}

+ Tạo services.xml định nghĩa service (hoặc có thể phát sinh ra .wsdl file bằng lệnh ant generate.wsdl)
<service name="businessService" scope="application"
targetNamespace="http://service.sample.org/">
<description> Business Service </description>
<messageReceivers>
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only"
class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</messageReceivers>
<schema schemaNamespace="http://service.sample.org/xsd"/>
<parameter name="ServiceClass"> org.sample.service.BusinessService</parameter>
</service>
+ Sử dụng ant để biên dịch và phát sinh .aar file
<project name="webservice" basedir="." default="generate.service">

<property environment="env"/>
<property name="AXIS2_HOME" value="D:/Java/Library/axis2-1.3"/>

<property name="build.dir" value="build"/>

<path id="axis2.classpath">
<fileset dir="${AXIS2_HOME}/lib">
<include name="*.jar"/>
</fileset>
</path>

<target name="compile.service">
<mkdir dir="${build.dir}"/>
<mkdir dir="${build.dir}/classes"/>

<!--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="org.sample.service.BusinessService"
outputLocation="${build.dir}"
targetNamespace="http://service.sample.org/"
schemaTargetNamespace="http://service.sample.org/xsd">
<classpath>
<pathelement path="${axis2.classpath}"/>
<pathelement location="${build.dir}/classes"/>
</classpath>
</java2wsdl>
</target>

<target name="generate.service" depends="compile.service">


<!--aar them up -->
<copy toDir="${build.dir}/classes" failonerror="false">
<fileset dir="${basedir}/resources">
<include name="**/*.xml"/>
</fileset>
</copy>
<jar destfile="${build.dir}/BusinessService.aar">
<fileset excludes="**/Test.class" dir="${build.dir}/classes"/>
</jar>
</target>

<target name="clean">
<delete dir="${build.dir}"/>
</target>
</project>

+ Deploy service bằng hai cách:


Sử dụng trang upload để upload .aar file hoặc bỏ trực tiếp vào C:\Program Files\Apache Software
Foundation\Tomcat 6.0\webapps\axis2\WEB-INF\services

+ Kiểm tra thông tin service


http://127.0.0.1:8989/axis2/services/listServices <= liệt kê tất cả service được deploy
http://127.0.0.1:8989/axis2/services/businessService?wsdl <= file mô tả webservice
http://127.0.0.1:8989/axis2/services/businessService?xsd <= file định nghĩa XML scheme
http://127.0.0.1:8989/axis2/services/businessService/calShippingCode?weight=25 <= gọi hàm và cung cấp giá trị
cho tham số weight

+ Viết lớp client gọi businessService:


BusinessTest.java
package org.sample.service;

import javax.xml.namespace.QName;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;

public class BusinessTest {


public static void main(String[] args) throws AxisFault {
RPCServiceClient serviceClient = new RPCServiceClient();

Options options = serviceClient.getOptions();


EndpointReference targetEPR = new EndpointReference(
"http://127.0.0.1:8989/axis2/services/businessService");
options.setTo(targetEPR);

// calculate shipping code


QName calShippingCode = new QName("http://service.sample.org/xsd",
"calShippingCode");

// Constructing the arguments array for the method invocation


Object[] opWeightArgs = new Object[] { new Integer(2), new Float(45.6) };
Class[] returnTypes = new Class[] { Float.class };

// Invoking the method


Object[] response = serviceClient.invokeBlocking(calShippingCode,
opWeightArgs, returnTypes);
Float shippingCode = (Float) response[0];
System.out.println("Shipping Code:" + shippingCode);
}
}

III. Deploy POJO Spring:

+ Service class
PersonService.java
package org.sample.service;

import org.sample.model.Person;

public class PersonService {

private Person person;

public Person getPerson() {


return person;
}

public void setPerson(Person person) {


this.person = person;
}

+ Model class
Person.java

package org.sample.model;

public class Person {

private Integer personId;

private String personName;

private String address;

public Integer getPersonId() {


return personId;
}

public void setPersonId(Integer personId) {


this.personId = personId;
}

public String getPersonName() {


return personName;
}

public void setPersonName(String personName) {


this.personName = personName;
}

public String getAddress() {


return address;
}

public void setAddress(String address) {


this.address = address;
}

+ applicationContext.xml (without a ServletContext)


<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-
beans.dtd">
<beans>
<bean id="applicationContext"
class="org.apache.axis2.extensions.spring.receivers.ApplicationContextHolder"/>

<bean id="person" class="org.sample.model.Person">


<property name="personName" value="Trinh"/>
<property name="address" value="CMT8"/>
</bean>

<bean id="personSpringService" class="org.sample.service.PersonService">


<property name="person" ref="person"/>
</bean>
</beans>

+ services.xml
<serviceGroup>
<service name="SpringInit" class="org.sample.service.SpringInit">
<description> This web service initializes Spring. </description>
<parameter name="ServiceClass">
org.sample.service.SpringInit</parameter>
<parameter name="ServiceTCCL">composite</parameter>
<parameter name="load-on-startup">true</parameter>
<operation name="springInit">
<messageReceiver
class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/>
</operation>
</service>
</serviceGroup>

+ Client class
PersonSpringClient.java

package org.sample.client;

import javax.xml.namespace.QName;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;
import org.sample.model.Person;

public class PersonSpringClient {

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


RPCServiceClient serviceClient = new RPCServiceClient();

Options options = serviceClient.getOptions();

EndpointReference targetEPR = new EndpointReference(


"http://127.0.0.1:8989/axis2/services/PersonSpringService");

options.setTo(targetEPR);

// Setting the weather


QName opSetPerson = new QName("http://service.sample.org", "setPerson");

Person person = new Person();


person.setPersonId(new Integer(3));
person.setPersonName("Trinh Nguyen");
person.setAddress("CMT8, District 3");

Object[] opSetPersonArgs = new Object[] { person };

serviceClient.invokeRobust(opSetPerson, opSetPersonArgs);

// Getting the person


QName opGetPerson = new QName("http://service.sample.org", "getPerson");

Object[] opGetPersonArgs = new Object[] {};


Class[] returnTypes = new Class[] { Person.class };

Object[] response = serviceClient.invokeBlocking(opGetPerson,


opGetPersonArgs, returnTypes);

Person result = (Person) response[0];

if (result == null) {
System.out.println("Person doesn't exist!");
return;
}

// Displaying the result


System.out.println("PersonId : " + result.getPersonId());
System.out.println("PersonName : " + result.getPersonName());
System.out.println("Address : " + result.getAddress());

}
}

+ Project layout
+ Tạo aar file
build.xml
<project name="pojospring" basedir="." default="generate.service">

<property environment="env"/>
<property name="service-name" value="PersonSpringService"/>
<property name="dest.dir" value="target"/>
<property name="axis2.home" value="D:/Java/Library/axis2-1.3"/>

<property name="repository.path" value="${axis2.home}/repository"/>

<property name="dest.dir.classes" value="${dest.dir}/classes"/>

<property name="dest.dir.lib" value="${dest.dir}/lib"/>

<property name="catalina-modules"
value="${env.CATALINA_HOME}/webapps/axis2/WEB-INF/services"/>

<path id="build.class.path">
<fileset dir="${axis2.home}/lib">
<include name="*.jar"/>
</fileset>
<!--add downloaded spring jars to classpath-->
<fileset dir="lib">
<include name="*.jar"/>
</fileset>
</path>
<path id="client.class.path">
<pathelement location="${dest.dir.classes}"/>
<fileset dir="${axis2.home}/lib">
<include name="*.jar"/>
</fileset>
</path>

<target name="clean">
<delete dir="${dest.dir}"/>
</target>

<target name="clean.libs">
<delete dir="lib"/>
</target>

<target name="prepare" depends="clean">

<mkdir dir="${dest.dir}"/>

<mkdir dir="${dest.dir.classes}"/>

<mkdir dir="${dest.dir.classes}/META-INF"/>
<antcall target="download.jars"/>
</target>

<target name="generate.service" depends="prepare">

<mkdir dir="${dest.dir}"/>

<mkdir dir="${dest.dir.classes}"/>
<mkdir dir="${dest.dir.classes}/META-INF"/>

<copy file="src/META-INF/services.xml"
tofile="${dest.dir.classes}/META-INF/services.xml" overwrite="true"/>
<copy file="src/applicationContext.xml"
tofile="${dest.dir.classes}/applicationContext.xml"
overwrite="true"/>

<javac debug="on" srcdir="src" destdir="${dest.dir.classes}"


includes="org/**">
<classpath refid="build.class.path"/>
</javac>

<jar basedir="${dest.dir.classes}"
destfile="${dest.dir}/${service-name}.aar"/>

<copy file="${dest.dir}/${service-name}.aar"
tofile="${repository.path}/services/${service-name}.aar"
overwrite="true"/>
</target>

<target name="rpc.client">
<antcall target="rpc.client.run"/>
</target>

<target name="rpc.client.compile" depends="prepare">


<javac debug="on" srcdir="src" destdir="${dest.dir.classes}"
includes="org/sample/client/**">
<classpath refid="build.class.path"/>
</javac>
</target>

<target name="rpc.client.run" depends="rpc.client.compile">


<echo message="${ant.file}"/>
<java classname="org.sample.client.PersonSpringRPCClient">
<classpath refid="client.class.path"/>
</java>
</target>

<target name="copy.to.tomcat" depends="generate.service">


<copy file="${dest.dir}/${service-name}.aar" todir="${catalina-modules}"/>
</target>

<!--We are not shipping spring jar with the release. This target can be used to
download spring jar to run this sample.-->
<target name="checkSpringJarAvailability">

<!--if either one of jar is not available, spring_available will set to false-->
<condition property="spring_available">
<and>
<available file="lib/spring-core-1.2.8.jar"/>
<available file="lib/spring-context-1.2.8.jar"/>
<available file="lib/spring-beans-1.2.8.jar"/>
</and>
</condition>
</target>

<target name="download.jars" depends="checkSpringJarAvailability"


unless="spring_available">
<echo message="Spring jars not available.Downloading...."/>
<mkdir dir="lib"/>
<get

src="http://ws.zones.apache.org/repository/org.springframework/jars/spring-core-
1.2.8.jar"
dest="lib/spring-core-1.2.8.jar" verbose="true"/>
<get

src="http://ws.zones.apache.org/repository/org.springframework/jars/spring-context-
1.2.8.jar"
dest="lib/spring-context-1.2.8.jar" verbose="true"/>
<get

src="http://ws.zones.apache.org/repository/org.springframework/jars/spring-beans-
1.2.8.jar"
dest="lib/spring-beans-1.2.8.jar" verbose="true"/>
</target>
</project>

+ Thư viện cần thiết


log4j.jar
commons-logging-1.1.jar
spring-context-1.2.8.jar
spring-beans-1.2.8.jar
spring-core-1.2.8.jar
spring.jar
Copy jar files đến thư mục lib của tomcat_home

IV. Tích hợp Spring, Hibernate và Axis2:


+ Model class
Product.java
package org.sample.model;
import java.math.BigDecimal;

public class Product {

private Integer productId;

private String productName;

private String description;

private Float weight;

private BigDecimal price;

private Integer categoryId;

public Integer getCategoryId() {


return categoryId;
}

public void setCategoryId(Integer categoryId) {


this.categoryId = categoryId;
}

public Integer getProductId() {


return productId;
}

public void setProductId(Integer productId) {


this.productId = productId;
}

public String getProductName() {


return productName;
}

public void setProductName(String productName) {


this.productName = productName;
}

public String getDescription() {


return description;
}

public void setDescription(String description) {


this.description = description;
}

public Float getWeight() {


return weight;
}

public void setWeight(Float weight) {


this.weight = weight;
}

public BigDecimal getPrice() {


return price;
}

public void setPrice(BigDecimal price) {


this.price = price;
}
}
Category.java
package org.sample.model;

public class Category {

private Integer categoryId;

private String categoryName;

public Integer getCategoryId() {


return categoryId;
}

public void setCategoryId(Integer categoryId) {


this.categoryId = categoryId;
}

public String getCategoryName() {


return categoryName;
}

public void setCategoryName(String categoryName) {


this.categoryName = categoryName;
}

Product.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.sample.model">
<class name="Product" table="PRODUCT">
<id name="productId" column="PRODUCT_ID" type="java.lang.Integer">
<generator class="increment"/>
</id>
<property name="productName" type="java.lang.String"
column="PRODUCT_NAME"/>
<property name="description" type="java.lang.String" column="DESCRIPTION"/>
<property name="weight" type="java.lang.Float" column="WEIGHT"/>
<property name="price" type="java.math.BigDecimal" column="PRICE"/>
<property name="categoryId" type="java.lang.Integer" column="CATEGORY_ID"/>
</class>
</hibernate-mapping>

Category.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.sample.model">
<class name="Category" table="CATEGORY">
<id name="categoryId" column="CATEGORY_ID" type="java.lang.Integer">
<generator class="increment"/>
</id>
<property name="categoryName" type="java.lang.String"
column="CATEGORY_NAME"/>
</class>
</hibernate-mapping>

+ Dao class
ProductDAO.java
package org.sample.dao;

import org.sample.model.Product;

public interface ProductDAO {


public void createProduct(Product product);

public void updateProduct(Product product);

public void deleteProduct(Product product);

public Product getProduct(Integer productId);

public Product[] listAllProduct();


}

CategoryDAO.java
package org.sample.dao;

import org.sample.model.Category;

public interface CategoryDAO {

public void createCategory(Category cat);

public void updateCategory(Category cat);

public void deleteCategory(Category cat);

public Category getCategory(Integer categoryId);

public Category[] getAllCategories();

ProductDAOImpl.java
package org.sample.dao.impl;

import org.sample.dao.ProductDAO;
import org.sample.model.Product;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class ProductDAOImpl extends HibernateDaoSupport implements ProductDAO {

public void createProduct(Product product) {


getHibernateTemplate().save(product);
}

@SuppressWarnings("unchecked")
public Product[] listAllProduct() {
Product[] products = new Product[0];
return (Product[]) getHibernateTemplate().find("from
Product").toArray(products);
}

public Product getProduct(Integer productId) {


Product pro1 = (Product) getHibernateTemplate().load(Product.class,
productId);
Product pro2 = new Product();
pro2.setProductId(pro1.getProductId());
pro2.setProductName(pro1.getProductName());
pro2.setCategoryId(pro1.getCategoryId());
pro2.setPrice(pro1.getPrice());
pro2.setWeight(pro1.getWeight());
pro2.setDescription(pro1.getDescription());
return pro2;
}

public void updateProduct(Product product) {


getHibernateTemplate().update(product);
}

public void deleteProduct(Product product) {


getHibernateTemplate().delete(product);
}

CategoryDAOImpl.java
package org.sample.dao.impl;

import java.util.List;

import org.sample.dao.CategoryDAO;
import org.sample.model.Category;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class CategoryDAOImpl extends HibernateDaoSupport implements CategoryDAO {

public void createCategory(Category cat) {


getHibernateTemplate().save(cat);
}

public void deleteCategory(Category cat) {


getHibernateTemplate().delete(cat);
}

@SuppressWarnings("unchecked")
public Category[] getAllCategories() {
List list = getHibernateTemplate().find("from Category");
Category[] categories = (Category[]) list.toArray();
return categories;
}

public void updateCategory(Category cat) {


getHibernateTemplate().update(cat);
}

public Category getCategory(Integer categoryId) {


Category cat1 = (Category) getHibernateTemplate().get(Category.class,
categoryId);
Category cat2 = new Category();
cat2.setCategoryId(cat1.getCategoryId());
cat2.setCategoryName(cat1.getCategoryName());
return cat2;
}
}

+ Service class (call dao)


ProductService.java
CategoryService.java
ProductServiceImpl.java
CategoryServiceImpl.java
+ applicationContext.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-
beans.dtd">
<beans>
<bean id="applicationContext"
class="org.apache.axis2.extensions.spring.receivers.ApplicationContextHolder"/>

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/product_management</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>root</value>
</property>
</bean>

<bean id="hibernateInterceptor"
class="org.springframework.orm.hibernate3.HibernateInterceptor">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>

<!-- Hibernate SessionFactory -->


<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref local="dataSource"/>
</property>
<property name="mappingResources">
<list>
<value>org/sample/model/Category.hbm.xml</value>
<value>org/sample/model/Product.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>

<!--######################### Transaction AOP


########################################-->

<bean id="hibernateTemplate"
class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>

<!-- ========================= BUSINESS OBJECT DEFINITIONS =========================


-->
<bean id="productDao" class="org.sample.dao.impl.ProductDAOImpl">
<property name="hibernateTemplate">
<ref local="hibernateTemplate"/>
</property>
</bean>

<bean id="productServiceTarget"
class="org.sample.service.impl.ProductServiceImpl">
<property name="productDao">
<ref local="productDao"/>
</property>
</bean>

<bean id="productService"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<ref local="productServiceTarget"/>
</property>
<property name="proxyInterfaces">
<value> org.sample.service.ProductService </value>
</property>
<property name="interceptorNames">
<list>
<value>hibernateInterceptor</value>
</list>
</property>
</bean>

<!-- Category Service -->


<bean id="categoryDao" class="org.sample.dao.impl.CategoryDAOImpl">
<property name="hibernateTemplate">
<ref local="hibernateTemplate"/>
</property>
</bean>

<bean id="categoryServiceTarget"
class="org.sample.service.impl.CategoryServiceImpl">
<property name="categoryDao">
<ref local="categoryDao"/>
</property>
</bean>

<bean id="categoryService"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<ref local="categoryServiceTarget"/>
</property>
<property name="proxyInterfaces">
<value> org.sample.service.CategoryService </value>
</property>
<property name="interceptorNames">
<list>
<value>hibernateInterceptor</value>
</list>
</property>
</bean>
</beans>

+ services.xml
<serviceGroup>
<service name="SpringInit" class="org.sample.service.SpringInit">
<description> This web service initializes Spring. </description>
<parameter name="ServiceClass">
org.sample.service.SpringInit</parameter>
<parameter name="ServiceTCCL">composite</parameter>
<parameter name="load-on-startup">true</parameter>
<operation name="springInit">
<messageReceiver
class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/>
</operation>
</service>
<service name="productService">
<parameter name="ServiceClass">
org.sample.service.impl.ProductServiceImpl</parameter>
<parameter name="ServiceObjectSupplier">

org.apache.axis2.extensions.spring.receivers.SpringAppContextAwareObjectSupplier</parameter>
<parameter name="SpringBeanName">productService</parameter>
<messageReceivers>
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only"
class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</messageReceivers>
</service>
<service name="categoryService">
<parameter name="ServiceClass">
org.sample.service.impl.CategoryServiceImpl</parameter>
<parameter name="ServiceObjectSupplier">

org.apache.axis2.extensions.spring.receivers.SpringAppContextAwareObjectSupplier</parameter>
<parameter name="SpringBeanName">categoryService</parameter>
<messageReceivers>
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only"
class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</messageReceivers>
</service>
</serviceGroup>

+ Client class
CreateProductSpringClient.java
UpdateProductSpringClient.java
package org.sample.client;

import javax.xml.namespace.QName;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;
import org.sample.model.Category;

public class UpdateCategorySpringClient {


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

RPCServiceClient serviceClient = new RPCServiceClient();

Options options = serviceClient.getOptions();

EndpointReference targetEPR = new EndpointReference(


"http://127.0.0.1:8989/axis2/services/categoryService");
options.setTo(targetEPR);

// get products
QName opGetCategory = new QName("http://impl.service.sample.org",
"getCategory");

Object[] opGetCategoryArgs = new Object[] { new Integer(4) };


Class[] returnTypes = new Class[] { Category.class };

Object[] response = serviceClient.invokeBlocking(opGetCategory,


opGetCategoryArgs, returnTypes);

Category cat = (Category) response[0];

// Displaying the result


System.out.println("CategoryId : " + cat.getCategoryId());
System.out.println("CategoryName : " + cat.getCategoryName());

// update Product
EndpointReference targetEPR1 = new EndpointReference(
"http://127.0.0.1:8989/axis2/services/categoryService");

options.setTo(targetEPR1);

cat.setCategoryName("Games");

Object[] opGetCategoryArgs1 = new Object[] { cat };

System.out.println("Category id:" + cat.getCategoryId());

QName opGetCategory1 = new QName("http://impl.service.sample.org",


"updateCategory");

serviceClient.invokeRobust(opGetCategory1, opGetCategoryArgs1);

System.out.println("xong roi");
}
}

DeleteProductSpringClient.java
ListProductSpringClient.java
package org.sample.client;

import javax.xml.namespace.QName;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;
import org.sample.model.Product;

public class ListProductSpringClient {


public static void main(String[] args) throws AxisFault {
RPCServiceClient serviceClient = new RPCServiceClient();

Options options = serviceClient.getOptions();

EndpointReference targetEPR = new EndpointReference(


"http://127.0.0.1:8989/axis2/services/productService");

options.setTo(targetEPR);

// get products
QName opGetProduct = new QName("http://impl.service.sample.org",
"listAllProduct");

Object[] opGetProductArgs = new Object[] {};


Class[] returnTypes = new Class[] { Product[].class };

Object[] response = serviceClient.invokeBlocking(opGetProduct,


opGetProductArgs, returnTypes);

Product[] products = (Product[]) response[0];

for (int i = 0; i < products.length; i++) {


Product pro = (Product) products[i];
System.out.println("product name:" + pro.getProductName());
}
}
}

+ Library
cglib.jar
common-collection.jar
ehcache.jar
dom4j.jar
jta.jar
hibernate3.jar
mysql-connector.jar
antlr-2.7.5H3.jar

Chú ý: copy tất cả thư mục con của thư mục classes trong thư mục target vào C:\Program Files\Apache Software
Foundation\Tomcat 6.0\webapps\axis2\WEB-INF\classes

Tip
+ Lỗi java.lang.IllegalStateException: No valid ObjectCreator found <= thiếu stax-1.2.0.jar file
+ Có thể sử dụng eclipse plugin để phát sinh WSDL file: http://ws.apache.org/axis2/tools/index.html
+ SOAP: nghi thức trao đổi thông tin qua HTTP, SOAP message là XML message
+ JAX-WS là kỹ thuật để xây dựng web service và client giao tiếp qua XML
+ JAX-RPC cung cấp mô hình để phát triển ứng dụng dựa vào SOAP. Lập trình JAX-RPC đơn giản kỹ thuật chạy
nghi thức SOAP và cung cấp ánh xạ services giữa Java và WSDL
+ WSDL: file mô tả web service
+ Sử dụng tool java2wsdl để phát sinh wsdl file: java2wsdl -cp . -cn org.sample.service.BusinessService -of
BusinessService.wsdl
+ POJO nhấn mạnh đối tượng là đối tượng Java bình thường (hông phải Enterprise JavaBean, nó không cài đặt, kế
thừa bất kỳ lớp nào hoặc chứa annotation) để thiết kế đơn giản hơn, tốt hơn. JavaBean là một POJO có tính chất
serializable (cho phép truy cập các thuộc tính private của các đối tượng persistent), có phương thức khởi tạo không
tham số, cho phép truy cập các thuộc tính bằng phương thức getter và setter.
(Spring POJO: http://www.onjava.com/pub/a/onjava/2005/06/29/spring-ejb3.html)

También podría gustarte