Professional Documents
Culture Documents
Chuong 3
Chuong 3
Chng 3 Pht trin Web Service vi cc cng ngh chun ca java Bi vit gm 6 phn: I. Gii thiu II. Tng quan cc cng ngh III. Cc cng ngh nn tng ca Web Service IV. Cc cng ngh ca Java h tr Web Service V. Cc cng c s dng cc cng ngh ca Java cho web VI. M hnh lp trnh
I. Gii thiu 1. Mc ch Gii thiu v hng dn s dng cc cng ngh v cng c chun do Sun cung cp lm vic vi Web Service. 2. Ngi c Yu cu c kin thc c bn v t duy lp trnh v ngn ng Java. 3. Tham kho http://www.w3.org/2002/ws/ http://ws.apache.org/ http://java.sun.com/webservices/ II. Tng quan cc cng ngh
III. Cc cng ngh nn tng ca Web Service 1. XML (eXtensible Markup Language) tr thnh chun cho vic m t d liu c trao i trn nn web.
Ths. Nguyn Trng Dng Trng HSP H Ni
L ngn ng nh du, s dng cc th (tag) nh du ni dung ca vn bn v nh ngha cu trc ca thng tin. Vd:
<element name="locateCustomer"> <complexType> <sequence> <element name="FirstName" type="xs:string"/> <element name="LastName" type="xs:string"/> <element name="Address" type="USAddress"/> </sequence> </complexType> </element> <element name="locateCustomerResponse"> <complexType> <sequence> <element name="CustomerRecord" type="CustomerRecord"/> </sequence> </complexType> </element>
Ti liu XML phi tun theo mt cu trc chun (Well-formed). Ti liu XML thng c kt hp vi lc XML (XML Schema) quy nh c php v cu trc cc th c s dng trong ti liu XML. Do c cc tnh cht trn nn ti liu XML c th d dng c x l bi cc ng dng v XML l ngn ng d liu cho Web Service.
Figure 3 Mt SOAP Message L giao thc cp cao da vo XML trao i thng tin trong cc h thng phn tn. SOAP cung cp mt nh dng chung cho cc d liu c trao i gia client v server. n v trao i thng tin c bn ca SOAP l 1 SOAP message. SOAP Message chnh l mt SOAP Envelope trong cha SOAP Body v c th cha SOAP Header. SOAP Envelope xc nh XML Namespace v loi encoding c s dng trong SOAP message. SOAP header c s dng cho cc ng dng quyt nh vic x l SOAP message nh th no. Vd:
3. WSDL (Web Service Definition Language) Client v server giao tip vi nhau thng qua vic gi cc SOAP message. WSDL nh ngha ra ni dung v cu trc ca SOAP message . WSDL l ti liu XML ng m t interface ca Web service. Ti liu WSDL nh ngha mt lc XML cho vic m t web service. Vd:
<definitions targetNamespace="http://endpoint.helloservice/" name="HelloService" xmlns:tns="http://endpoint.helloservice/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <types> <xsd:schema> <xsd:import namespace="http://endpoint.helloservice/" schemaLocation="http://localhost:8080/hello/hello?xsd=1"/> </xsd:schema> </types> <message name="sayHello"> <part element="tns:sayHello" name="parameters"/> </message> <message name="sayHelloResponse"> <part element="tns:sayHelloResponse" name="parameters"/> </message> <message name="getUserBean">
Ths. Nguyn Trng Dng Trng HSP H Ni
<part element="tns:getUserBean" name="parameters"/> </message> <message name="getUserBeanResponse"> <part element="tns:getUserBeanResponse" name="parameters"/> </message> <message name="Exception"> <part element="tns:Exception" name="Exception"/> </message> <portType name="Hello"> <operation name="sayHello"> <input message="tns:sayHello"/> <output message="tns:sayHelloResponse"/> </operation> <operation name="getUserBean"> <input message="tns:getUserBean"/> <output message="tns:getUserBeanResponse"/> <fault message="tns:Exception" name="Exception"/> </operation> </portType> <binding type="tns:Hello" name="HelloPortBinding"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="sayHello"> <soap:operation soapAction=""/> <input> <soap:body use="literal"/> </input> <output> <soap:body use="literal"/> </output> </operation> <operation name="getUserBean">
Ths. Nguyn Trng Dng Trng HSP H Ni
<soap:operation soapAction=""/> <input> <soap:body use="literal"/> </input> <output> <soap:body use="literal"/> </output> <fault name="Exception"> <soap:fault use="literal" name="Exception"/> </fault> </operation> </binding> <service name="HelloService"> <port binding="tns:HelloPortBinding" name="HelloPort"> <soap:address location="http://localhost:8080/hello/hello"/> </port> </service> </definitions> IV. Cc cng ngh ca Java h tr Web Service 1. JAXP (Java API for XML Processing) L mt tp hp cc API cho vic x l ti liu XML Bao gm cc tp API con x l ti liu XML nh DOM, SAX. 2. JAX-RPC (Java API for XML Remote Produce Call) Tp hp cc API cung cp cc service bng XML-RPC. Cho php Java gi cc phng thc ca Web Service thng qua cc h thng phn tn. Khng gii hn vic s dng nn Java cho c client v server. Client s dng JAX-RPC c th gi Web Service trn cc nn tng khc nhau. Client khng dng Java cng c th gi cc Web Service s dng cng ngh Java vi Jax-RPC. c thit k n gin vic s dng SOAP. Lp trnh vin khng cn phi lm cng vic x l trc tip vi SOAP m ch cn s dng ngn ng Java v cc tp API ca Java.
Ths. Nguyn Trng Dng Trng HSP H Ni
T phin bn WSDP 2.0. JAX-RPC c t tn li thnh JAX-WS. 3. JAXB (Java API for XML Data Binding) Cung cp cc phng thc mapping ti liu XML thnh 1 tp hp cc i tng Java v cc Interface da trn lc XML. Lm vic trc tip vi XML thay v phi x l ni dung XML. Cng vic c thc hin vi 2 bc chnh l: o S dng b binding compiler c cung cp vi JAXB binding lc XML thnh cc i class Java v cc interface. o S dng cc phng thc gn kt d liu XML vi cc class v interface c to ra. 4. SAAJ (SOAP with Attachment API for Java) Mt tp hp API tun theo c t SOAP with Attachment. Dng to ra SOAP message c hoc khng c nh km d liu nh phn. 5. XWS (XML and Web Service Sercurity) Cung cp bo mt cp SOAP message cho cc ng dng s dng JAX-RPC. Thng tin bo mt c cha trong SOAP header. Mc ch dng chng cc s truy cp tri php khi message c gi trn ng truyn. V. Cc cng c s dng cc cng ngh ca Java cho web service.
1. APT Apt l cng c cung cp phng tin cho vic x l cc annotation c thm vo trong Java bi JSR 175. JSR 175 cho php lp trnh vin khai bo nhng loi b ngha cu trc mi kt hp vi thnh phn trng, phng thc, class. Ant task cho apt c cung cp bi JAX-WS Vd:
<apt
verbose="true|false"
Ths. Nguyn Trng Dng Trng HSP H Ni
classpath="classpath"
nocompile="true|false"
print="true|false"
factorypath="<path>"
xlistannotationtypes="true|false"
xlistdeclarations="true|false"
xprintaptrounds="true|false"
xprintfactoryinfo="true|false"
xclassesasdecls="true|false"
debug="true|false"
debuglevel="lines|vars|source"
nowarn="true|false"
Ths. Nguyn Trng Dng Trng HSP H Ni
deprecation="true|false"
bootclasspath="<path>"
extdirs="<path>"
endorseddirs="<path>"
sourcepath="<path>"
Bng cc tu chn ca cng c apt verbose: In ra thng bo classpath: ng dn n cc class v th vin destdir: Xc nh ni cha cc class c bin dch sourcedestdir: Xc nh ni cha cc file source java c to ra nocompile: Khng bin dch cc file source java print: In ra my in debug: To ra cc thng tin debug debuglevel: Cp debug: lines, vars, sources nowarn: Khng to ra cc cnh bo sourcepath: Xc nh ng dn n cc file source java
Ths. Nguyn Trng Dng Trng HSP H Ni
encoding: Xc nh encoding c s dng cho cc file source java target: To ra cc file class ng vi mt phin bn nht nh option: Cc tu chn i vi b x l annotation Vd:
<apt destdir="src" sourcedestdir="src" sourcepath="src" classpathref="project.classpath"> <source dir="src"> <include name="**/*.java" /> </source> </apt>
2. WSImport Cng c t ng to ra cc file class v source java lm vic vi web service da vo ti liu wsdl. WSImport Ant task c cung cp bi JAX-WS. Bng cc tu chn ca wsimport wsdl WSDL file destdir:Xc nh ng dn cha cc file class c to ra sourcedestdir:Xc nh ng dn cha cc file source java c to ra verbose: Hin thng bo binding: Xc nh find dng binding d liu package: Xc nh package Vd:
<target name="import-webservice"> <echo message="Import web service ..." /> <wsimport destdir="src" sourcedestdir="src" wsdl="http://localhost:8080/hello/hello?wsdl"> </wsimport> </target>
Ths. Nguyn Trng Dng Trng HSP H Ni
VI. M hnh lp trnh Chng ta s xy dng mt ng dng web service nh th hin cc cng c v cng ngh java cho web service. ng dng ny c mt web service end point cung cp hai phng thc n gin String sayHello(String name) v UserBean getUserBean(String userName).
1. Server
Figure 4 Cu trc cy th mc Cc bc c bn to mt ng dng web service pha server o Vit cc file java
Ths. Nguyn Trng Dng Trng HSP H Ni
o S dng cng c apt to ra cc file class cho web service. o ng gi cc class v resourse thnh ng dng web (file war). o Trin khai ng dng. Yu cu phi c ci j2sdk 1.5.06 v c tt c cc th vin trong b WSDP 2.0. Bin dch cc file java ch tng thch vi phin bn java 1.5.
1.1. Vit cc file Java Vit cc java bean c dng lu tr d liu c truyn gia client v server. Document.java
package helloservice.endpoint;
import java.util.Date;
UserBean.java
package helloservice.endpoint;
package helloservice.endpoint;
import java.util.Date;
@WebService() public class Hello { private String message = new String("Hello, ");
return userBean; } }
Trong thy trong file java thi hnh web service c s dng cc annotation. o @WebService c s dng nh du mt lp Java l thi hnh web service hoc l nh du mt interface nh ngha web service interface. o @WebMethod lm cho mt phng thc tr thnh mt phng thc web service.
1.2. S dng cng cng c apt bin dch Chng ta phi m bo cc th vin ca WSDP u c trong class path. To file build.xml. nh ngha apt ant task:
Ths. Nguyn Trng Dng Trng HSP H Ni
<target name="build"> <echo message="${ant.project.name}: ${ant.file}" /> <javac destdir="src"> <src path="src" /> <classpath refid="project.classpath" /> </javac> <apt destdir="src" sourcedestdir="src" sourcepath="src" classpathref="project.classpath"> <source dir="src"> <include name="**/*.java" /> </source> </apt> </target>
Chng ta s dng cu lnh ant build chy file build.xml t dng lnh hoc c th s dng Eclipse chy file build.xml. Sau khi build xong chng ta s thy apt to thm mt s file java cho web service.
1.3. ng gi thnh ng dng web Vit file cu hnh nh ngha web service sun-jaxws.xml vi ni dung sau
Th endpoint dng nh ngha mt web service end point. Thuc tnh name xc nh tn ca web service. Thuc tnh implementation xc nh lp thc thi web service. urlpattern l ng dn tng i ca ng dng vi ng dng web chng ta trin khai web service (http://localhost:8080/hello/hello). Vit file cu hnh web cho ng dng web: web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>HelloService</display-name> <listener> <listenerclass>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class> </listener> <servlet> <display-name>HelloService</display-name> <servlet-name>HelloService</servlet-name> <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloService</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping>
Ths. Nguyn Trng Dng Trng HSP H Ni
Tng ng vi mi web service c nh ngha trong file sun-jaxws.xml chng ta s nh ngha mt servlet trong file web.xml. Display name v servlet name c cng tn vi web service, servlet class l mc nh. url-pattern tng ng vi url-pattern ca web service trong file sun.jaxws.xml.
To thm mt target create-war trong file build.xml ng gi ng dng thnh ng dng web.
<target name="create-war" description="Packages the WAR file" depends="build"> <echo message="Creating the WAR...." /> <delete file="hello.war" /> <war warfile="hello.war" webxml="webconfig/web.xml"> <webinf dir="webconfig" includes="*.xml" excludes="web.xml" /> <zipfileset dir="webconfig" includes="*.wsdl, *.xsd" prefix="/WEB-INF/wsdl" /> <lib dir="C:/libs/jaxb" /> <lib dir="C:/libs/jaxp/endorsed" /> <lib dir="C:/libs/jaxr" /> <lib dir="C:/libs/jaxws" /> <lib dir="C:/libs/jwsdp" /> <lib dir="C:/libs/saaj" /> <lib dir="C:/libs/sjsxp" /> <lib dir="C:/libs/xws" /> <classes dir="src" excludes="**/*.java" /> </war> </target>
Ths. Nguyn Trng Dng Trng HSP H Ni
Build t dng lnh vi cu lnh ant create-war hoc build t trong Eclipse. Chng ta s nhn c mt file l hello.war.
1.4. Trin khai ng dng Copy file war vo web server tomcat 5.5 hoc JBoss 4.03 sau g vo trnh duyt dng sau kim tra: http://localhost:8080/hello/hello?wsdl ---------------------------------------------------http://javasimple.wordpress.com Mt s ng dn n cc file th vin trong bi v d mnh vit ng dn tuyt i. Cc bn khi download v th phi sa cho ng vi ng dn trn my ca bn mi chy c. ---------------------------------------------------http://javasimple.wordpress.com 2. Client
Figure 5 Cu trc cy th mc nh ngha wsimport ant task trong file build.xml <taskdef classpathref="project.classpath" name="wsimport" classname="com.sun.tools.ws.ant.WsImport"> </taskdef> To mt target import-webservice: <target name="import-webservice"> <echo message="Import web service ..." /> <wsimport destdir="src" sourcedestdir="src" wsdl="http://localhost:8080/hello/hello?wsdl"> </wsimport> </target>
Sau khi chy target import-webservice chng ta s nhn c cc file java tng ng lm vic vi web service pha server. Vit mt lp Run kim tra
Ths. Nguyn Trng Dng Trng HSP H Ni
Run.java
package helloservice.endpoint;
import javax.xml.ws.WebServiceRef;
try {
Ths. Nguyn Trng Dng Trng HSP H Ni
userBean=client.getUserBean("linhpk"); document=userBean.getDocument();
} catch (Exception_Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } I. Nhng thit lp cn thit cho dch v web vit bng Java 1. Danh sch cc tp tin cn ti xung a) Apache Tomcat (phin bn 5.0.30) http://www.apache.org b) Apache Axis (phin bn 1.4) http://xml.apache.org/axis/index.html c) Xerces (version 2.6.2) http://xml.apache.org/dist/xerces-j/ Ch : l phin bn mi nht khi vit bi ny, c th c nhng bn mi hn ti cc a ch trn
2. Ci t Apache Tomcat Chng ta c th ti tomcat c tn jakarta-tomcat-5.0.30.zip ti a ch http://www.apache.org. Ri bn c th ci t hoc gii nn n. Ti gi s bn ci t hoc gii nn Apache tomcat trong th mc G:\WebService\tomcat v th mc v th mc JDK l G:\WebService\j2sdk1.4.2_11
Ths. Nguyn Trng Dng Trng HSP H Ni
3. Cu hnh bin mi trng By gi tt c th vin ca Apache tomcat c ci t trn my ca bn, bn cn phi ch cho Java bit v tr ca chng. iu ny c th thc hin bng cch thit thng qua bin mi trng CLASSPATH. set JAVA_HOME=G:\WebService\j2sdk1.4.2_11 set CATALINA_HOME=G:\WebService\tomcat set CATALINA_LIB=%CATALINA_HOME%\common\lib set CLASSPATH=%CLASSPATH%;.;%CATALINA_LIB%\mail.jar; %CATALINA_LIB%\activation.jar;%CATALINA_LIB%\servlet.jar set PATH=%PATH%;%JAVA_HOME%\bin;%CATALINA_HOME%\bin
4. iu kin cn thit s dng Apache Axis Ti gi s rng bn ci t Apache Axis vo th mc G:\WebService\axis. Sau , bn phi thit lp bin mi trng n cc th vin Apache Axis
set AXIS_LIB=G:\WebService\axis\lib set CLASSPATH=%CLASSPATH%; %AXIS_LIB%\axis.jar; %AXIS_LIB%\axis-ant.jar; %AXIS_LIB%\commons-discovery.jar; %AXIS_LIB%\commons-logging.jar; %AXIS_LIB%\jaxrpc.jar; %AXIS_LIB%\log4j-1.2.8.jar; %AXIS_LIB%\saaj.jar; %AXIS_LIB%\wsdl4j.jar Sau khi thit lp y cc th vin cho Apache Axis, bn cn to mt ng dn ng cnh ng dng web n th mc G:\WebService\axis\webapps\axis hoc chp th mc G:\WebService\axis\webapps\axis vo trong th mc G:\WebService\tomcat\webapps. Sau bn khi ng my ch web bng lnh: startup.
Ths. Nguyn Trng Dng Trng HSP H Ni
II. Tch hp Java v .NET s dch v web 1. Vit dch v web bng Axis v .NET Trong phn ny, chng ta s tch hp dch v web vit bng ngn ng java s dng th vin Apache Axis vi dch v web vit bng ngn ng.NET. Chng ta s vit 2 dch v web bng cch s dng th vin Apache Axis v .NET. Sau chng ta s vit 2 chng trnh bng ngn ng Java v .NET s dng cc dch v web ny. Di y l m hnh minh ha v d
namespace CsharpService { [WebService(Namespace="net")] public class NetService : System.Web.Services.WebService { [WebMethod] public string getCSharpMessage() { return "This is message from MS .NET"; } } }
Ths. Nguyn Trng Dng Trng HSP H Ni
Tip theo l dch v web bng ngn ng Java s dng th vin Apache Axis
public class Axis { public String getAxisMessage() throws Exception { return "This is message from Apache Axis"; } }
i tn tp tin thnh Axis.jws, Chp n vo th mc G:\WebService\tomcat\webapps\axis and restart Apache Tomcat. 2. Tip n chng ta s to cc chng trnh pha ngi dng bng ngn ng Java v .NET s dng cc dch v web trn Trc khi chng ta vit mt ng dng .NET dng cc dch v web ny th chng ta phi to WSDL chng trnh.NET c th tham chiu n cc dch v web. i vi dch v web vit bng Apache Axis th chng ta s dng URL: http://localhost:8080/axis/Axis.jws?wsdl tham chiu n dch v web Apache Axis V y l m ngun ca ng dng.NET s dng cc dch v web k trn
using System; namespace CsharpClient { class Csharp { public CSharp() { //Call .NET Web Service NetRef.NetService net = new NetRef.NetService(); Console.WriteLine(net.getCSharpMessage()); AxisRef.AxisService axis = new AxisRef.AxisService(); Console.WriteLine(axis.getAxisMessage()); Console.Read(); } static void Main(string[] args) {
Ths. Nguyn Trng Dng Trng HSP H Ni
CSharp cs = new CSharp(); } } } Vi NetRef, AxisRef l cc tn tham chiu n dch v web tng ng vi cc dch v web vit bng.NET v Apache Axis Tip n chng ta s vit ng dng Java s dng cc dch v web trn. gi cc dch v ny, chng ta phi to cc proxy n cc dch v web ny.Lnh di y dng to mt proxy ca java n dch v web ca .NET java org.apache.axis.wsdl.WSDL2Java http://localhost/CSharpService/NetService.asmx?wsdl
Tip n, chng ta s to proxy n dch v web vit bng Apache Axis,tng t nh dch v web ca .NET chng ta ch cn thay th URL ca dch v web vit bng .NET bng dch v vit bng Apache Axis nh sau: java org.apache.axis.wsdl.WSDL2Java -p axis http://localhost:8080/axis/Axis.jws?wsdl Sau khi chng ta to cc proxy java n cc dch v web ny chng ta s c cc th mc cha cc lp proxy n cc dch v ny c tn tng ng l net v axis By gi chng ta c th vit chng trnh bng ngn ng Java s dng cc dch v web trn
import axis. *; import net.*; public class GetAllType { public static void main(String [] args) throws Exception { //Call MS .NET NetServiceLocator netLocator = new NetServiceLocator(); NetServiceSoap net = netLocator.getNetServiceSoap(); System.out.println(net.getCSharpMessage()); //Call Apache Axis AxisServiceLocator axisLocator = new AxisServiceLocator();
Ths. Nguyn Trng Dng Trng HSP H Ni