Top Banner
Tutorial Web Service (Web & Client) with Spring Web Service arifnasution@ymailcom
24

Tutorial web service (web & client) with spring web services

Dec 05, 2014

Download

Education

 
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Tutorial web service (web & client) with spring web services

Tutorial Web Service (Web & Client) with Spring Web Service

arifnasution@ymailcom

Page 2: Tutorial web service (web & client) with spring web services

Tutorial Web Service (Service & Client) with Spring Web Services

Pendahuluan Alhamdulillah, tanggal 22 mei 2013 penulis berhasil menambahkan tutorial gratis dengan judul Tutorial Web Service

(Service & client) with Spring Web Services. Kenapa saya menggunakan framework Spring ? karena dari semua

framework JAVA yang ada, Spring merupakan salah satu framework yang terkenal dan lengkap dokumentasinya

sehingga semoga ketika pembaca sudah bisa membuat basic web services, detail penggunaan framework bisa dibantu

dokumentasi dari spring secara langsung. Selain itu, tutorial ini dibuat karena penulis merasa salah satu teori ataupun

framework tersulit untuk dipelajari adalah mengenai web service yang mana teknologi ke depan secara global akan

berbasis web.

Web service pada tutorial ini untuk melakukan proses seperti login dan merespon sesuai dengan username yang dikirim,

apabila username sama dengan arif, maka akan merespon guntank dan selain username tersebut service akan

merespon failed.

Pada tutorial ini, setidaknya yang harus dikuasai oleh pembaca adalah dasar-dasar algoritma, pemrograman JAVA dan

penggunaan IDE Eclipse. Adapun teknologi dipakai :

Eclipse-jee-indigo-SR2-win32-x86_64

JDK 1.7.0_10

Apache Tomcat 6.0.35

Spring Framework 3.1.3

Spring Web Services 2.1.1

Tutorial ini terdiri dari :

Pembuatan Web Service

Pembuatan Web Service Client

Beberapa saran dari saya untuk mengikuti tutorial ini :

Sudah memiliki semua jar Spring Framework & Spring Web Services (bisa di download di website resmi).

Sudah memiliki jar common logging & wsdl4j (bisa di download di website resmi).

Dimana web service maupun web service client dibuat dalam satu project.

Akhir kata, tutorial ini masih banyak kekurangan dan dibuat hanya berdasarkan iseng dan mencoba berbagi sedikit ilmu

yang dimiliki. Oleh karena itu, apabila ada saran maupun kritik bisa melalui email [email protected].

Marifnst, 2013-05-22

Page 3: Tutorial web service (web & client) with spring web services

Service 1. Buat dynamic web project, “New” – “Dynamic Web Project”.

2. Berikan “Project Name” & klik next.

Page 4: Tutorial web service (web & client) with spring web services

3. Klik next.

4. Klik finish, pastikan generate web.xml dalam kondisi di cek.

Page 5: Tutorial web service (web & client) with spring web services

5. Ambil file jar dari file spring ws seperti di gambar.

6. Copy jar tersebut ke dalam project, WebContent – WEB-INF - lib.

Page 6: Tutorial web service (web & client) with spring web services

7. Klik kanan folder project, pilih “properties”.

8. Pilih java build path, klik add jar.

Page 7: Tutorial web service (web & client) with spring web services

9. Masuk ke folder lib dari jar, pilih ok.

10. Jar akan bertambah, pilih ok.

Page 8: Tutorial web service (web & client) with spring web services

11. Masuk ke web.xml & tambahkan baris seperti di gambar (code bisa dilihat di lampiran).

12. Klik kanan WebContent – WEB-INF, “New” – “File” & beri nama login.xsd.

Page 9: Tutorial web service (web & client) with spring web services

13. Isi login.xsd (code bisa dilihat di lampiran).

14. Buat file baru pada WebContent – WEB-INF, beri nama spring-ws-servlet.xml (code bisa dilihat di lampiran).

Page 10: Tutorial web service (web & client) with spring web services

15. Klik kanan folder src pada “Java Resources”, buat package baru dengan nama terserah anda (disini saya beri

nama sample.springws).

16. Klik kanan package yang sudah dibuat, “New” – “Class”.

Page 11: Tutorial web service (web & client) with spring web services

17. Beri nama class tersebut terserah anda (disini saya beri nama OrderEndPoint).

18. Isi OrderEndPoint.java (code bisa dilihat di Lampiran).

Page 12: Tutorial web service (web & client) with spring web services

19. Copy semua jar dari spring framework, untuk mencegah kekurangan dependency.

20. Paste jar tersebut ke dalam folder WebContent – WEB-INF – lib.

Page 13: Tutorial web service (web & client) with spring web services

21. Tambahkan jar tersebut ke dalam java build path seperti poin 8 - 10.

22. Tambahkan jar commons-loggin-<versi> & wsdl4j yang merupakan dependency jar yang dibutuhkan spring web

services. Jangan lupa menambahkan jar tersebut pada “Java Build Path”.

Page 14: Tutorial web service (web & client) with spring web services

23. Klik kanan folder project, “Run As” – “Run on Server”.

24. Pilih server yang digunakan (disini saya menggunakan Apache Tomcat 6) kemudian klik next.

Page 15: Tutorial web service (web & client) with spring web services

25. Pilih project yang akan di deploy ke server & klik finish.

26. Eclipse akan menampilkan status 405.

Page 16: Tutorial web service (web & client) with spring web services

27. Masuk ke url http://localhost:8080/<nama_project>/loginservices/login.wsdl, apabila berhasil maka xml wsdl

akan dimunculkan browser.

Page 17: Tutorial web service (web & client) with spring web services

Client 1. Klik kanan package yang sudah dibuat (dalam tutorial ini sample.springws), “New” – “Class”.

2. Saya beri nama SampleClient.java (code bisa dilihat di lampiran).

Page 18: Tutorial web service (web & client) with spring web services

3. Copy semua jar dari spring ws, <folder spring ws> - dist – modules.

4. Copy ke folder lib dan jangan lupa tambahkan pada “Java Build Path” (caranya bisa dilihat pada poin

sebelumnya).

Page 19: Tutorial web service (web & client) with spring web services

5. Klik kanan class tersebut, “Run As” – “Java Application”.

6. Apabila berhasil, maka aplikasi java akan melakukan print pada console seperti gambar di bawah. Itu berarti

client sudah berhasil melakukan request service dan mendapat respon dari web service yang sudah dibuat.

Page 20: Tutorial web service (web & client) with spring web services

Source Code

Web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

id="WebApp_ID" version="2.5">

<display-name>TutorialWebService</display-name>

<welcome-file-list>

<welcome-file>index.html</welcome-file>

<welcome-file>index.htm</welcome-file>

<welcome-file>index.jsp</welcome-file>

<welcome-file>default.html</welcome-file>

<welcome-file>default.htm</welcome-file>

<welcome-file>default.jsp</welcome-file>

</welcome-file-list>

<display-name>My Service</display-name>

<servlet>

<servlet-name>spring-ws</servlet-name>

<servlet-

class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>

<init-param>

<param-name>transformWsdlLocations</param-name>

<param-value>true</param-value>

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>spring-ws</servlet-name>

<url-pattern>/*</url-pattern>

</servlet-mapping>

</web-app>

Page 21: Tutorial web service (web & client) with spring web services

spring-ws-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:sws="http://www.springframework.org/schema/web-services"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/web-services

http://www.springframework.org/schema/web-services/web-services-2.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<description>

This web application context contains Spring-WS beans. The

beans defined

in this context are automatically

detected by Spring-WS,

similar to the way Controllers are picked up in Spring

Web MVC.

</description>

<context:component-scan base-package="sample.springws" />

<sws:annotation-driven />

<sws:dynamic-wsdl id="login" portTypeName="login"

locationUri="loginservices">

<sws:xsd location="/WEB-INF/login.xsd" />

</sws:dynamic-wsdl>

</beans>

Page 22: Tutorial web service (web & client) with spring web services

Login.xsd

<?xml version="1.0" encoding="UTF-8"?>

<schema xmlns="http://www.w3.org/2001/XMLSchema"

targetNamespace="http://www.springwssample.org/types"

xmlns:tns="http://www.springwssample.org/types" elementFormDefault="qualified">

<element name="loginRequest">

<complexType>

<sequence>

<element name="username" type="string" />

<element name="password" type="string" />

</sequence>

</complexType>

</element>

<element name="loginResponse">

<complexType>

<sequence>

<element name="message" type="string" />

</sequence>

</complexType>

</element>

</schema>

Page 23: Tutorial web service (web & client) with spring web services

OrderEndPoint.java

package sample.springws;

import java.io.IOException;

import java.util.HashMap;

import java.util.Map;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

import org.springframework.ws.server.endpoint.annotation.Endpoint;

import org.springframework.ws.server.endpoint.annotation.PayloadRoot;

import org.springframework.ws.server.endpoint.annotation.RequestPayload;

import org.springframework.ws.server.endpoint.annotation.ResponsePayload;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import org.w3c.dom.NodeList;

@Endpoint

public class OrderEndpoint {

private static final String NAMESPACE = "http://www.springwssample.org/types";

@PayloadRoot(localPart = "loginRequest", namespace =

"http://www.springwssample.org/types")

@ResponsePayload

public Element loginServiceProcess(@RequestPayload Element request)

throws ParserConfigurationException, IOException {

// iterasi value xml request ke dalam map

Map<String, String> requestValue = new HashMap<>();

NodeList nl = request.getChildNodes();

for (int i=0;i < nl.getLength();i++) {

requestValue.put(nl.item(i).getNodeName(), nl.item(i).getTextContent());

}

String message = "Failed";

if (requestValue.get("username").equals("arif")) {

message = "guntank";

}

// membuat response xml

Document document = DocumentBuilderFactory.newInstance()

.newDocumentBuilder().newDocument();

Element response = document.createElementNS(NAMESPACE, "loginResponse");

response.appendChild(addElementWithValue(document, "message", message));

return response;

}

private Element addElementWithValue(Document document, String element,

String value) {

Element child = document.createElementNS(NAMESPACE, element);

child.appendChild(document.createTextNode(value));

return child;

}

}

Page 24: Tutorial web service (web & client) with spring web services

SampleClient.java

package sample.springws;

import java.io.IOException;

import java.io.StringReader;

import java.io.StringWriter;

import javax.xml.transform.stream.StreamResult;

import javax.xml.transform.stream.StreamSource;

import org.springframework.oxm.XmlMappingException;

import org.springframework.ws.client.core.WebServiceTemplate;

public class SampleClient {

public static void main(String[] args) throws XmlMappingException,

IOException {

String SAMPLE_MESSAGE_1 = "<loginRequest

xmlns=\"http://www.springwssample.org/types\">"

+ "<username>arif</username>"

+ "<password>password</password>"

+ "</loginRequest>";

StreamSource source = new StreamSource(new StringReader(SAMPLE_MESSAGE_1));

StringWriter strwr = new StringWriter();

StreamResult result = new StreamResult(strwr);

WebServiceTemplate webServiceTemplate = new WebServiceTemplate();

webServiceTemplate.sendSourceAndReceiveToResult("http://localhost:8080/TutorialWebService

/loginservices", source, result);

System.out.println("response for first message : " + strwr);

String SAMPLE_MESSAGE_2 = "<loginRequest

xmlns=\"http://www.springwssample.org/types\">"

+ "<username>other</username>"

+ "<password>password</password>"

+ "</loginRequest>";

source = new StreamSource(new StringReader(SAMPLE_MESSAGE_2));

strwr = new StringWriter();

result = new StreamResult(strwr);

webServiceTemplate.sendSourceAndReceiveToResult("http://localhost:8080/TutorialWebService

/loginservices", source, result);

System.out.println("response for second message : " + strwr);

}

}