Java WebServices Tutorial From JavaTpoint
Java WebServices Tutorial From JavaTpoint
c o m |1
Web service is a technology to communicate one programming language with another. For example,
java programming language can interact with PHP and .Net by using web services. In other words, web
service provides a way to achieve interoperability.
There are two ways to write the code for JAX-WS by RPC style and Document style. Like JAX-WS, JAX-
RS can be written by Jersey and RESTeasy. We will learn all these technologies later.
Problem
Web services tutorial is developed and tested carefully. But if you find any problem or mistake in our
tutorial, you can report to us. We assure, you will not find any problem in web services tutorial.
As you can see in the figure, java, .net or PHP applications can communicate with other applications
through web service over the network. For example, java application can interact with Java, .Net and
PHP applications. So web service is a language independent way of communication.
1. SOAP
2. WSDL
J ava We b S e r v i c e s Tu to r i a l - J ava Tp o i nt . c o m |3
3. UDDI
SOAP
SOAP is an acronym for Simple Object Access Protocol.
SOAP is XML based, so it is platform independent and language independent. In other words, it can be
used with Java, .Net or PHP language on any platform.
WSDL
WSDL is an acronym for Web Services Description Language.
WSDL is a xml document containing information about web services such as method name, method
parameter and how to access it.
UDDI
UDDI is an acronym for Universal Description, Discovery and Integration.
UDDI is a XML based framework for describing, discovering and integrating web services.
UDDI is a directory of web service interfaces described by WSDL, containing information about web
services.
SOAP is XML based protocol. It is platform independent and language independent. By using SOAP, you
will be able to interact with other programming language applications.
Language and Platform independent: SOAP web services can be written in any programming
language and executed in any platform.
WSDL dependent: SOAP uses WSDL and doesn't have any other mechanism to discover the service.
Language and Platform independent: RESTful web services can be written in any programming
language and executed in any platform.
Can use SOAP: RESTful web services can use SOAP web services as the implementation.
Permits different data format: RESTful web service permits different data format such as Plain Text,
HTML, XML and JSON.
There are many differences between SOAP and REST web services. The important 10 differences between SOAP and
REST are given below:
2) SOAP stands for Simple Object REST stands for REpresentational State Transfer.
Access Protocol.
3) SOAP can't use REST because it is REST can use SOAP web services because it is a
a protocol. concept and can use any protocol like HTTP, SOAP.
4) SOAP uses services interfaces to REST uses URI to expose business logic.
expose the business logic.
5) JAX-WS is the java API for SOAP JAX-RS is the java API for RESTful web services.
web services.
6) SOAP defines standards to be REST does not define too much standards like SOAP.
strictly followed.
7) SOAP requires more REST requires less bandwidth and resource than
bandwidth and resource than REST.
REST.
8) SOAP defines its own security. RESTful web services inherits security
measures from the underlying transport.
9) SOAP permits XML data format REST permits different data format such as Plain
only. text, HTML, XML, JSON etc.
10) SOAP is less preferred than REST. REST more preferred than SOAP.
Service
A service is well-defined, self-contained function that represents unit of functionality. A service can
exchange information from another service. It is not dependent on the state of another service.
J ava We b S e r v i c e s Tu to r i a l - J ava Tp o i nt . c o m |6
Service Connections
The figure given below illustrates the service oriented architecture. Service consumer sends service
request to the service provider and service provider sends the service response to the service
consumer. The service connection is understandable to both service consumer and service provider.
Java web service application perform communication through WSDL (Web Services Description
Language). There are two ways to write java web service application code: SOAP and RESTful.
1) JAX-WS: for SOAP web services. The are two ways to write JAX-WS application code: by RPC style
and Document style.
2) JAX-RS: for RESTful web services. There are mainly 2 implementation currently in use for creating
JAX-RS application: Jersey and RESTeasy.
J ava We b S e r v i c e s Tu to r i a l - J ava Tp o i nt . c o m |7
JAX-WS Tutorial
JAX-WS tutorial is provides concepts and examples of JAX-WS API. This JAX-WS tutorial is designed
for beginners and professionals.
1. RPC style
2. Document style
RPC Style
1) RPC style web services use method name and parameters to generate XML structure.
WSDL file:
1. <types/>
1. <message name="getHelloWorldAsString">
2. <part name="arg0" type="xsd:string"/>
3. </message>
4. <message name="getHelloWorldAsStringResponse">
5. <part name="return" type="xsd:string"/>
6. </message>
3. <operation name="getHelloWorldAsString">
4. <soap:operation soapAction=""/>
5. <input>
6. <soap:body use="literal" namespace="http://javatpoint.com/"/>
7. </input>
8. <output>
9. <soap:body use="literal" namespace="http://javatpoint.com/"/>
10. </output>
11. </operation>
12. </binding>
Document Style
1) Document style web services can be validated against predefined schema.
WSDL file:
1. <types>
2. <xsd:schema>
3. <xsd:import namespace="http://javatpoint.com/" schemaLocation="http://localhost:7779/ws/
hello?xsd=1"/>
4. </xsd:schema>
5. </types>
1. <message name="getHelloWorldAsString">
2. <part name="parameters" element="tns:getHelloWorldAsString"/>
3. </message>
4. <message name="getHelloWorldAsStringResponse">
5. <part name="parameters" element="tns:getHelloWorldAsStringResponse"/>
6. </message>
7. </input>
8. <output>
9. <soap:body use="literal"/>
10. </output>
11. </operation>
12. </binding>
JAX-WS API is inbuilt in JDK, so you don't need to load any extra jar file for it. Let's see a simple
example of JAX-WS example in RPC style.
1. HelloWorld.java
2. HelloWorldImpl.java
3. Publisher.java
4. HelloWorldClient.java
The first 3 files are created for server side and 1 application for client side.
File: HelloWorld.java
1. package com.javatpoint;
2. import javax.jws.WebMethod;
3. import javax.jws.WebService;
4. import javax.jws.soap.SOAPBinding;
5. import javax.jws.soap.SOAPBinding.Style;
6. //Service Endpoint Interface
7. @WebService
8. @SOAPBinding(style = Style.RPC)
9. public interface HelloWorld{
10. @WebMethod String getHelloWorldAsString(String name);
11. }
File: HelloWorldImpl.java
1. package com.javatpoint;
2. import javax.jws.WebService;
3. //Service Implementation
4. @WebService(endpointInterface = "com.javatpoint.HelloWorld")
5. public class HelloWorldImpl implements HelloWorld{
6. @Override
7. public String getHelloWorldAsString(String name) {
8. return "Hello World JAX-WS " + name;
9. }
10. }
File: Publisher.java
J a v a W e b S e r v i c e s T u t o r i a l - J a v a T p o i n t . c o m | 11
1. package com.javatpoint;
2. import javax.xml.ws.Endpoint;
3. //Endpoint publisher
4. public class HelloWorldPublisher{
5. public static void main(String[] args) {
6. Endpoint.publish("http://localhost:7779/ws/hello", new HelloWorldImpl());
7. }
8. }
After running the publisher code, you can see the generated WSDL file by visiting the URL:
1. http://localhost:7779/ws/hello?wsdl
File: HelloWorldClient.java
1. package com.javatpoint;
2. import java.net.URL;
3. import javax.xml.namespace.QName;
4. import javax.xml.ws.Service;
5. public class HelloWorldClient{
6. public static void main(String[] args) throws Exception {
7. URL url = new URL("http://localhost:7779/ws/hello?wsdl");
8.
9. //1st argument service URI, refer to wsdl document above
10. //2nd argument is service name, refer to wsdl document above
11. QName qname = new QName("http://javatpoint.com/", "HelloWorldImplService");
12. Service service = Service.create(url, qname);
13. HelloWorld hello = service.getPort(HelloWorld.class);
14. System.out.println(hello.getHelloWorldAsString("javatpoint rpc"));
15. }
16. }
Output:
You need to use Style.DOCUMENT for @SOAPBinding annotation in place of Style.RPC. Let's have a
quick look at this:
J a v a W e b S e r v i c e s T u t o r i a l - J a v a T p o i n t . c o m | 12
File: HelloWorld.java
There are created 4 files for hello world JAX-WS document style example:
1. HelloWorld.java
2. HelloWorldImpl.java
3. Publisher.java
4. HelloWorldClient.java
The first 3 files are created for server side and 1 application for client side.
File: HelloWorld.java
1. package com.javatpoint;
2. import javax.jws.WebMethod;
3. import javax.jws.WebService;
4. import javax.jws.soap.SOAPBinding;
5. import javax.jws.soap.SOAPBinding.Style;
6. //Service Endpoint Interface
7. @WebService
8. @SOAPBinding(style = Style.DOCUMENT)
9. public interface HelloWorld{
10. @WebMethod String getHelloWorldAsString(String name);
11. }
File: HelloWorldImpl.java
1. package com.javatpoint;
2. import javax.jws.WebService;
3. //Service Implementation
4. @WebService(endpointInterface = "com.javatpoint.HelloWorld")
5. public class HelloWorldImpl implements HelloWorld{
6. @Override
7. public String getHelloWorldAsString(String name) {
8. return "Hello World JAX-WS " + name;
9. }
10. }
File: Publisher.java
1. package com.javatpoint;
2. import javax.xml.ws.Endpoint;
3. //Endpoint publisher
4. public class HelloWorldPublisher{
5. public static void main(String[] args) {
6. Endpoint.publish("http://localhost:7779/ws/hello", new HelloWorldImpl());
7. }
8. }
J a v a W e b S e r v i c e s T u t o r i a l - J a v a T p o i n t . c o m | 13
After running the publisher code, you can see the generated WSDL file by visiting the URL:
1. http://localhost:7779/ws/hello?wsdl
File: HelloWorldClient.java
1. package com.javatpoint;
2. import java.net.URL;
3. import javax.xml.namespace.QName;
4. import javax.xml.ws.Service;
5. public class HelloWorldClient{
6. public static void main(String[] args) throws Exception {
7. URL url = new URL("http://localhost:7779/ws/hello?wsdl");
8.
9. //1st argument service URI, refer to wsdl document above
10. //2nd argument is service name, refer to wsdl document above
11. QName qname = new QName("http://javatpoint.com/", "HelloWorldImplService");
12. Service service = Service.create(url, qname);
13. HelloWorld hello = service.getPort(HelloWorld.class);
14. System.out.println(hello.getHelloWorldAsString("javatpoint document"));
15. }
16. }
Output:
JAX-RS Tutorial
JAX-RS tutorial is provides concepts and examples of JAX-RS API. This JAX-RS tutorial is designed for
beginners and professionals.
1. Jersey
2. RESTEasy
J a v a W e b S e r v i c e s T u t o r i a l - J a v a T p o i n t . c o m | 14
In this example, we are using jersey jar files for using jersey example for JAX-RS.
1. Hello.java
2. web.xml
3. index.html
J a v a W e b S e r v i c e s T u t o r i a l - J a v a T p o i n t . c o m | 15
4. HelloWorldClient.java
The first 3 files are created for server side and 1 application for client side.
File: Hello.java
1. package com.javatpoint.rest;
2. import javax.ws.rs.GET;
3. import javax.ws.rs.Path;
4. import javax.ws.rs.Produces;
5. import javax.ws.rs.core.MediaType;
6. @Path("/hello")
7. public class Hello {
8. // This method is called if HTML and XML is not requested
9. @GET
10. @Produces(MediaType.TEXT_PLAIN)
11. public String sayPlainTextHello() {
12. return "Hello Jersey Plain";
13. }
14. // This method is called if XML is requested
15. @GET
16. @Produces(MediaType.TEXT_XML)
17. public String sayXMLHello() {
18. return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
19. }
20.
21. // This method is called if HTML is requested
22. @GET
23. @Produces(MediaType.TEXT_HTML)
24. public String sayHtmlHello() {
25. return "<html> " + "<title>" + "Hello Jersey" + "</title>"
26. + "<body><h1>" + "Hello Jersey HTML" + "</h1></body>" + "</html> ";
27. }
28. }
File: web.xml
18. <url-pattern>/rest/*</url-pattern>
19. </servlet-mapping>
20. </web-app>
File: index.html
Now run this application on server. Here we are using Tomcat server on port 4444. The project name is
restfuljersey.
After running the project, you will see the following output:
The ClientTest.java file is created inside the server application. But you can run client code by other
application also by having service interface and jersey jar file.
File: ClientTest.java
1. package com.javatpoint.restclient;
2. import java.net.URI;
3. import javax.ws.rs.client.Client;
4. import javax.ws.rs.client.ClientBuilder;
5. import javax.ws.rs.client.WebTarget;
6. import javax.ws.rs.core.MediaType;
7. import javax.ws.rs.core.UriBuilder;
8. import org.glassfish.jersey.client.ClientConfig;
9. public class ClientTest {
10. public static void main(String[] args) {
11. ClientConfig config = new ClientConfig();
12. Client client = ClientBuilder.newClient(config);
13. WebTarget target = client.target(getBaseURI());
14. //Now printing the server code of different media type
15. System.out.println(target.path("rest").path("hello").request().accept(MediaType.TEXT_PLAIN
).get(String.class));
16. System.out.println(target.path("rest").path("hello").request().accept(MediaType.TEXT_XML).
get(String.class));
J a v a W e b S e r v i c e s T u t o r i a l - J a v a T p o i n t . c o m | 17
17. System.out.println(target.path("rest").path("hello").request().accept(MediaType.TEXT_HTML
).get(String.class));
18. }
19. private static URI getBaseURI() {
20. //here server is running on 4444 port number and project name is restfuljersey
21. return UriBuilder.fromUri("http://localhost:4444/restfuljersey").build();
22. }
23. }
Output:
Click me to download JAX-RS example using eclipse without jersey jar files.
JAX-RS Annotations
The javax.ws.rs package contains JAX-RS annotations.
Annotation Description
Produces defines media type for the response such as XML, PLAIN, JSON etc. It defines the
media type that the methods of a resource class or MessageBodyWriter can
produce.
Consumes It defines the media type that the methods of a resource class or
MessageBodyReader can produce.
1. package com.javatpoint.rest;
2. import javax.ws.rs.GET;
3. import javax.ws.rs.Path;
4. import javax.ws.rs.PathParam;
5. import javax.ws.rs.core.Response;
6. @Path("/hello")
7. public class HelloService{
8. @GET
9. @Path("/{param}")
10. public Response getMsg(@PathParam("param") String msg) {
11. String output = "Jersey say : " + msg;
12. return Response.status(200).entity(output).build();
13. }
14. }
File: web.xml
12. <param-value>com.javatpoint.rest</param-value>
13. </init-param>
14. <load-on-startup>1</load-on-startup>
15. </servlet>
16. <servlet-mapping>
17. <servlet-name>Jersey REST Service</servlet-name>
18. <url-pattern>/rest/*</url-pattern>
19. </servlet-mapping>
20. </web-app>
File: index.html
Now run this application on server, you will see the following output:
Output:
1. package com.javatpoint.rest;
2. import javax.ws.rs.GET;
3. import javax.ws.rs.Path;
4. import javax.ws.rs.PathParam;
5. import javax.ws.rs.core.Response;
6. @Path("/hello")
7. public class HelloService{
8. @GET
9. @Path("{year}/{month}/{day}")
10. public Response getDate(
11. @PathParam("year") int year,
12. @PathParam("month") int month,
13. @PathParam("day") int day) {
14.
15. String date = year + "/" + month + "/" + day;
16.
17. return Response.status(200)
18. .entity("getDate is called, year/month/day : " + date)
19. .build();
20. }
21. }
File: web.xml
File: index.html
J a v a W e b S e r v i c e s T u t o r i a l - J a v a T p o i n t . c o m | 20
Now run this application on server, you will see the following output:
Output:
1. package com.javatpoint.rest;
2. import javax.ws.rs.FormParam;
3. import javax.ws.rs.POST;
4. import javax.ws.rs.Path;
5. import javax.ws.rs.core.Response;
6. @Path("/product")
7. public class ProductService{
8. @POST
9. @Path("/add")
10. public Response addUser(
11. @FormParam("id") int id,
12. @FormParam("name") String name,
13. @FormParam("price") float price) {
14.
15. return Response.status(200)
16. .entity(" Product added successfuly!<br> Id: "+id+"<br> Name: " + name+"<br> Pric
e: "+price)
17. .build();
18. }
19. }
File: web.xml
File: index.html
Now run this application on server, you will see the following output:
Output:
J a v a W e b S e r v i c e s T u t o r i a l - J a v a T p o i n t . c o m | 21
You need to specify different content type to download different files. The @Produces annotation is
used to specify the type of file content.
1. package com.javatpoint.rest;
2. import java.io.File;
3. import javax.ws.rs.GET;
4. import javax.ws.rs.Path;
5. import javax.ws.rs.Produces;
6. import javax.ws.rs.core.Response;
7. import javax.ws.rs.core.Response.ResponseBuilder;
8. @Path("/files")
9. public class FileDownloadService {
10. private static final String FILE_PATH = "c:\\myfile.txt";
11. @GET
12. @Path("/txt")
13. @Produces("text/plain")
14. public Response getFile() {
15. File file = new File(FILE_PATH);
16.
17. ResponseBuilder response = Response.ok((Object) file);
18. response.header("Content-Disposition","attachment; filename=\"javatpoint_file.txt\"");
19. return response.build();
20.
21. }
22. }
File: web.xml
File: index.html
Now run this application on server, you will see the following output:
J a v a W e b S e r v i c e s T u t o r i a l - J a v a T p o i n t . c o m | 23
Output:
1. package com.javatpoint.rest;
2. import java.io.File;
3. import javax.ws.rs.GET;
4. import javax.ws.rs.Path;
5. import javax.ws.rs.Produces;
6. import javax.ws.rs.core.Response;
7. import javax.ws.rs.core.Response.ResponseBuilder;
8. @Path("/files")
9. public class FileDownloadService {
10. private static final String FILE_PATH = "c:\\myimage.png";
11. @GET
12. @Path("/image")
13. @Produces("image/png")
14. public Response getFile() {
15. File file = new File(FILE_PATH);
16. ResponseBuilder response = Response.ok((Object) file);
17. response.header("Content-Disposition","attachment; filename=\"javatpoint_image.png\"
");
18. return response.build();
19.
20. }
21. }
File: web.xml
File: index.html
J a v a W e b S e r v i c e s T u t o r i a l - J a v a T p o i n t . c o m | 24
1. package com.javatpoint.rest;
2. import java.io.File;
3. import javax.ws.rs.GET;
4. import javax.ws.rs.Path;
5. import javax.ws.rs.Produces;
6. import javax.ws.rs.core.Response;
7. import javax.ws.rs.core.Response.ResponseBuilder;
8. @Path("/files")
9. public class FileDownloadService {
10. private static final String FILE_PATH = "c:\\mypdf.pdf";
11. @GET
12. @Path("/pdf")
13. @Produces("application/pdf")
14. public Response getFile() {
15. File file = new File(FILE_PATH);
16. ResponseBuilder response = Response.ok((Object) file);
17. response.header("Content-Disposition","attachment; filename=\"javatpoint_pdf.pdf\"");
18. return response.build();
19. }
20. }
File: web.xml
File: index.html
The @FormDataParam("file") annotation is used to mention file parameter in the service class. The
@Consumes(MediaType.MULTIPART_FORM_DATA) is used to provide information of the file upload.
To upload file through jersey implementation, you need to provide extra configuration entry in web.xml
file.
1. <init-param>
2. <param-name>jersey.config.server.provider.classnames</param-name>
3. <param-value>org.glassfish.jersey.filter.LoggingFilter;
4. org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
5. </init-param>
Let's see the complete code to upload file using RESTful JAX-RS API.
1. package com.javatpoint.rest;
2. import java.io.File;
3. import java.io.FileOutputStream;
4. import java.io.IOException;
5. import java.io.InputStream;
6. import javax.ws.rs.Consumes;
7. import javax.ws.rs.POST;
8. import javax.ws.rs.Path;
9. import javax.ws.rs.core.MediaType;
10. import javax.ws.rs.core.Response;
11. import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
12. import org.glassfish.jersey.media.multipart.FormDataParam;
13. @Path("/files")
14. public class FileUploadService {
15. @POST
16. @Path("/upload")
17. @Consumes(MediaType.MULTIPART_FORM_DATA)
18. public Response uploadFile(
19. @FormDataParam("file") InputStream uploadedInputStream,
20. @FormDataParam("file") FormDataContentDisposition fileDetail) {
21. String fileLocation = "e://" + fileDetail.getFileName();
22. //saving file
23. try {
24. FileOutputStream out = new FileOutputStream(new File(fileLocation));
25. int read = 0;
26. byte[] bytes = new byte[1024];
27. out = new FileOutputStream(new File(fileLocation));
28. while ((read = uploadedInputStream.read(bytes)) != -1) {
29. out.write(bytes, 0, read);
30. }
31. out.flush();
32. out.close();
33. } catch (IOException e) {e.printStackTrace();}
34. String output = "File successfully uploaded to : " + fileLocation;
35. return Response.status(200).entity(output).build();
36. }
37. }
File: web.xml
File: index.html
Now run this application on server, you will see the following output:
Output: