Java WebServices Tutorial From JavaTpoint | Soap | Web Service

December 20, 2016 | Author: Anonymous | Category: Java
Share Embed


Short Description

Java WebServices Tutorial Collected From JavaTpoint by sumitav. ... As you can see in the figure, java, .net or PHP appl...

Description

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 |1

Java Web Services Tutorial from JavaTpoint.com Web Services Tutorial Web Services tutorial is designed for beginners and professionals providing basic and advanced concepts of web services such as protocols, SOAP, RESTful, java web service implementation, JAX-WS and JAX-RS tutorials and examples. 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.

Java Web Services Tutorial In this tutorial, you will be able to learn java web services and its specifications such as JAX-WS and JAX-RS. There are two ways to write the code for JAX-WS by RPC style and Document style. Like JAX-WS, JAXRS can be written by Jersey and RESTeasy. We will learn all these technologies later.

Web Services Examples In this tutorial, we will see a lot of web services examples like JAX-WS example by RPC style, JAX-WS example by document style, JAX-RS example by Jersey and JAX-RS example by RESTeasy implementation.

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.

What is Web Service A Web Service is can be defined by following ways:  

is a client server application or application component for communication. method of communication between two devices over network.

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 |2  

is a software system for interoperable machine to machine communication. is a collection of standards or protocols for exchanging information between two devices or application.

Let's understand it by the figure given below:

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.

Types of Web Services There are mainly two types of web services. 1. SOAP web services. 2. RESTful web services.

Web Service Components There are three major web service components. 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 a XML-based protocol for accessing web services. SOAP is a W3C recommendation for communication between applications. 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. WSDL is a part of UDDI. It acts as a interface between web service applications. WSDL is pronounced as wiz-dull.

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 Web Services SOAP stands for Simple Object Access Protocol. It is a XML-based protocol for accessing web services. SOAP is a W3C recommendation for communication between two applications.

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

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.

Advantages of Soap Web Services WS Security: SOAP defines its own security known as WS Security. Language and Platform independent: SOAP web services can be written in any programming language and executed in any platform.

Disadvantages of Soap Web Services Slow: SOAP uses XML format that must be parsed to be read. It defines many standards that must be followed while developing the SOAP applications. So it is slow and consumes more bandwidth and resource. WSDL dependent: SOAP uses WSDL and doesn't have any other mechanism to discover the service.

RESTful Web Services REST stands for REpresentational State Transfer. REST is an architectural style not a protocol.

Advantages of RESTful Web Services Fast: RESTful Web Services are fast because there is no strict specification like SOAP. It consumes less bandwidth and resource. 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.

SOAP vs REST Web Services

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

There are many differences between SOAP and REST web services. The important 10 differences between SOAP and REST are given below:

No.

SOAP

REST

1)

SOAP is a protocol.

REST is an architectural style.

2)

SOAP stands for Simple Object

REST stands for REpresentational State Transfer.

Access Protocol. 3)

4)

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.

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)

10)

SOAP permits XML data format

REST permits different data format such as Plain

only.

text, HTML, XML, JSON etc.

SOAP is less preferred than REST.

REST more preferred than SOAP.

Service Oriented Architecture (SOA) Service Oriented Architecture or SOA is a design pattern. It is designed to provide services to other applications through protocol. It is a concept only and not tied to any programming language or platform. Web services is a technology of SOA most likely.

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 Services Tutorial Java web services tutorial provides concepts and examples of two main java web services api: JAXWS and JAX-RS. The java web service application can be accessed by other programming languages such as .Net and PHP. 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.

Java Web Services API There are two main API's defined by Java for developing web service applications since JavaEE 6. 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

We will see full tutorials of JAX-WS and JAX-RS in next page.

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. There are two ways to develop JAX-WS example. 1. RPC style 2. Document style

Difference between RPC vs Document style web services Click me to see difference between RPC and Document

JAX-WS Example RPC Style

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 |8 Click me for JAX-WS Example RPC Style

JAX-WS Example Document Style Click me to see JAX-WS Example Document Style

Difference between RPC and Document web services There are many differences between RPC and Document web services. The important differences between RPC and Document are given below:

RPC Style 1) RPC style web services use method name and parameters to generate XML structure. 2) The generated WSDL is difficult to be validated against schema. 3) In RPC style, SOAP message is sent as many elements. 4) RPC style message is tightly coupled. 5) In RPC style, SOAP message keeps the operation name. 6) In RPC style, parameters are sent as discrete values. Let's see the RPC style generated WSDL file. WSDL file: In WSDL file, it doesn't specify the types details. 1.

For message part, it defines name and type attributes.

1. 2. 3. 4. 5. 6.

For soap:body, it defines use and namespace attributes.

1. 2.



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 |9 3. 4. 5. 6. 7. 8. 9. 10. 11. 12.



Document Style 1) Document style web services can be validated against predefined schema. 2) In document style, SOAP message is sent as a single document. 3) Document style message is loosely coupled. 4) In Document style, SOAP message loses the operation name. 5) In Document style, parameters are sent in XML format. Let's see the Document style generated WSDL file. WSDL file: In WSDL file, it specifies types details having namespace and schemaLocation. 1. 2. 3.

4. 5. For message part, it defines name and element attributes. 1. 2. 3. 4. 5. 6.

For soap:body, it defines use attribute only not namespace.

1. 2. 3. 4. 5. 6.



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 | 10 7. 8. 9. 10. 11. 12.



JAX-WS Example RPC Style Creating JAX-WS example is a easy task because it requires no extra configuration settings. 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. There are created 4 files for hello world JAX-WS example: 1. 2. 3. 4.

HelloWorld.java HelloWorldImpl.java Publisher.java HelloWorldClient.java

The first 3 files are created for server side and 1 application for client side.

JAX-WS Server Code File: HelloWorld.java 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.

package com.javatpoint; import javax.jws.WebMethod; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.jws.soap.SOAPBinding.Style; //Service Endpoint Interface @WebService @SOAPBinding(style = Style.RPC) public interface HelloWorld{ @WebMethod String getHelloWorldAsString(String name); }

File: HelloWorldImpl.java 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.

package com.javatpoint; import javax.jws.WebService; //Service Implementation @WebService(endpointInterface = "com.javatpoint.HelloWorld") public class HelloWorldImpl implements HelloWorld{ @Override public String getHelloWorldAsString(String name) { return "Hello World JAX-WS " + name; } }

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. 2. 3. 4. 5. 6. 7. 8.

package com.javatpoint; import javax.xml.ws.Endpoint; //Endpoint publisher public class HelloWorldPublisher{ public static void main(String[] args) { Endpoint.publish("http://localhost:7779/ws/hello", new HelloWorldImpl()); } }

How to view generated WSDL After running the publisher code, you can see the generated WSDL file by visiting the URL: 1.

http://localhost:7779/ws/hello?wsdl

JAX-WS Client Code File: HelloWorldClient.java 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16.

package com.javatpoint; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.Service; public class HelloWorldClient{ public static void main(String[] args) throws Exception { URL url = new URL("http://localhost:7779/ws/hello?wsdl");

}

//1st argument service URI, refer to wsdl document above //2nd argument is service name, refer to wsdl document above QName qname = new QName("http://javatpoint.com/", "HelloWorldImplService"); Service service = Service.create(url, qname); HelloWorld hello = service.getPort(HelloWorld.class); System.out.println(hello.getHelloWorldAsString("javatpoint rpc")); }

Output: Hello World JAX-WS javatpoint rpc Click me to download JAX-WS server example RPC style (eclipse) Click me to download JAX-WS client example RPC style (eclipse)

JAX-WS Example Document Style Like RPC style, we can create JAX-WS example in document style. To do so, you need to change only one line in service interface. 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 1.

@SOAPBinding(style = Style.DOCUMENT)//It is changed from RPC to DOCUMENT Now Let's see the full example of JAX-WS in document style. There are created 4 files for hello world JAX-WS document style example: 1. 2. 3. 4.

HelloWorld.java HelloWorldImpl.java Publisher.java HelloWorldClient.java

The first 3 files are created for server side and 1 application for client side.

JAX-WS Server Code File: HelloWorld.java 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.

package com.javatpoint; import javax.jws.WebMethod; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.jws.soap.SOAPBinding.Style; //Service Endpoint Interface @WebService @SOAPBinding(style = Style.DOCUMENT) public interface HelloWorld{ @WebMethod String getHelloWorldAsString(String name); }

File: HelloWorldImpl.java 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.

package com.javatpoint; import javax.jws.WebService; //Service Implementation @WebService(endpointInterface = "com.javatpoint.HelloWorld") public class HelloWorldImpl implements HelloWorld{ @Override public String getHelloWorldAsString(String name) { return "Hello World JAX-WS " + name; } }

File: Publisher.java 1. 2. 3. 4. 5. 6. 7. 8.

package com.javatpoint; import javax.xml.ws.Endpoint; //Endpoint publisher public class HelloWorldPublisher{ public static void main(String[] args) { Endpoint.publish("http://localhost:7779/ws/hello", new HelloWorldImpl()); } }

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

How to view generated WSDL After running the publisher code, you can see the generated WSDL file by visiting the URL: 1.

http://localhost:7779/ws/hello?wsdl

JAX-WS Client Code File: HelloWorldClient.java 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16.

package com.javatpoint; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.Service; public class HelloWorldClient{ public static void main(String[] args) throws Exception { URL url = new URL("http://localhost:7779/ws/hello?wsdl");

}

//1st argument service URI, refer to wsdl document above //2nd argument is service name, refer to wsdl document above QName qname = new QName("http://javatpoint.com/", "HelloWorldImplService"); Service service = Service.create(url, qname); HelloWorld hello = service.getPort(HelloWorld.class); System.out.println(hello.getHelloWorldAsString("javatpoint document")); }

Output: Hello World JAX-WS javatpoint document Click me to download JAX-WS server example Document style (eclipse) Click me to download JAX-WS client example Document style (eclipse)

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. There are two main implementation of JAX-RS API. 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

RESTful JAX-RS Example Jersey Click me to see JAX-RS example using Jersey implementation

JAX-WS Annotations Example JAX-RS annotations : @Path, @PathParam, @FormParam, @Produces, @Get, @Post

JAX-RS File Download Example JAX-RS Download Image File, Text File, PDF File, Excel File

JAX-RS File Upload Example Click me for RESTful JAX-RS File Upload example

JAX-RS Example Jersey We can create JAX-RS example by jersey implementation. To do so, you need to load jersey jar files or use maven framework. In this example, we are using jersey jar files for using jersey example for JAX-RS.

Click me to download jersey jar files.

There are created 4 files for hello world JAX-RS example: 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.

JAX-RS Server Code File: Hello.java 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28.

package com.javatpoint.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("/hello") public class Hello { // This method is called if HTML and XML is not requested @GET @Produces(MediaType.TEXT_PLAIN) public String sayPlainTextHello() { return "Hello Jersey Plain"; } // This method is called if XML is requested @GET @Produces(MediaType.TEXT_XML) public String sayXMLHello() { return "" + " Hello Jersey" + ""; } // This method is called if HTML is requested @GET @Produces(MediaType.TEXT_HTML) public String sayHtmlHello() { return " " + "" + "Hello Jersey" + "" + "" + "Hello Jersey HTML" + "" + " "; } }

File: web.xml 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17.

Jersey REST Service org.glassfish.jersey.servlet.ServletContainer jersey.config.server.provider.packages com.javatpoint.rest 1 Jersey REST Service

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 | 16 18. 19. 20.

/rest/*

File: index.html 1.

Click Here 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:

JAX-RS Client Code 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. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15.

package com.javatpoint.restclient; import java.net.URI; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; import org.glassfish.jersey.client.ClientConfig; public class ClientTest { public static void main(String[] args) { ClientConfig config = new ClientConfig(); Client client = ClientBuilder.newClient(config); WebTarget target = client.target(getBaseURI()); //Now printing the server code of different media type 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: Hello Jersey Plain Hello Jersey Hello JerseyHello Jersey HTML Click me to download JAX-RS example using eclipse without jersey jar files.

RESTful JAX-RS Annotations Example JAX-RS API provides following annotations to develop RESTful applications in java. We are using jersey implementation for developing JAX-RS examples.

Click me to download jersey jar files.

JAX-RS Annotations The javax.ws.rs

package contains JAX-RS annotations.

Annotation

Description

Path

It identifies the URI path. It can be specified on class or method.

PathParam

represents the parameter of the URI path.

GET

specifies method responds to GET request.

POST

specifies method responds to POST request.

PUT

specifies method responds to PUT request.

HEAD

specifies method responds to HEAD request.

DELETE

specifies method responds to DELETE request.

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 | 18

OPTIONS

specifies method responds to OPTIONS request.

FormParam

represents the parameter of the form.

QueryParam

represents the parameter of the query string of an URL.

HeaderParam

represents the parameter of the header.

CookieParam

represents the parameter of the cookie.

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.

JAX-RS @Path, @GET and @PathParam Annotations File: HelloService.java 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14.

package com.javatpoint.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; @Path("/hello") public class HelloService{ @GET @Path("/{param}") public Response getMsg(@PathParam("param") String msg) { String output = "Jersey say : " + msg; return Response.status(200).entity(output).build(); } }

File: web.xml 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.

Jersey REST Service org.glassfish.jersey.servlet.ServletContainer jersey.config.server.provider.packages

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 | 19 12. 13. 14. 15. 16. 17. 18. 19. 20.

com.javatpoint.rest 1 Jersey REST Service /rest/* File: index.html

1.

Click Here Now run this application on server, you will see the following output: Output: Jersey say : javatpoint Click me to download this example

JAX-RS Multiple @PathParam Annotation File: HelloService.java 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21.

package com.javatpoint.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; @Path("/hello") public class HelloService{ @GET @Path("{year}/{month}/{day}") public Response getDate( @PathParam("year") int year, @PathParam("month") int month, @PathParam("day") int day) { String date = year + "/" + month + "/" + day; return Response.status(200) .entity("getDate is called, year/month/day : " + date) .build(); }

}

File: web.xml It is same as above example.

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

Click Here Now run this application on server, you will see the following output: Output: getDate is called, year/month/day : 2014/12/5 Click me to download this example

JAX-RS @FormParam and @POST Annotation File: HelloService.java 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19.

package com.javatpoint.rest; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Response; @Path("/product") public class ProductService{ @POST @Path("/add") public Response addUser( @FormParam("id") int id, @FormParam("name") String name, @FormParam("price") float price) {

e: "+price)

return Response.status(200) .entity(" Product added successfuly! Id: "+id+" Name: " + name+" Pric

}

.build();

}

File: web.xml It is same as above example.

File: index.html 1. 2. 3. 4. 5. 6.

Enter Id: Enter Name: Enter Price: 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

Click me to download this example

RESTful JAX-RS File Download Example We can download text files, image files, pdf files, excel files in java by JAX-RS API. To do so we need to write few lines of code only. Here, we are using jersey implementation for developing JAX-RS file download examples. You need to specify different content type to download different files. The @Produces annotation is used to specify the type of file content. 1. 2. 3. 4. 5.

@Produces("text/plain"): for downloading text file. @Produces("image/png"): for downloading png image file. @Produces("application/pdf"): for downloading PDF file. @Produces("application/vnd.ms-excel"): for downloading excel file. @Produces("application/msword"): for downloading ms word file.

Click me to download jersey jar files.

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 | 22

JAX-RS Text File Download File: FileDownloadService.java 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22.

package com.javatpoint.rest; import java.io.File; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; @Path("/files") public class FileDownloadService { private static final String FILE_PATH = "c:\\myfile.txt"; @GET @Path("/txt") @Produces("text/plain") public Response getFile() { File file = new File(FILE_PATH); ResponseBuilder response = Response.ok((Object) file); response.header("Content-Disposition","attachment; filename=\"javatpoint_file.txt\""); return response.build(); } }

File: web.xml 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20.

Jersey REST Service org.glassfish.jersey.servlet.ServletContainer jersey.config.server.provider.packages com.javatpoint.rest 1 Jersey REST Service /rest/*

File: index.html 1.

Download Text File 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:

Click me to download this example

JAX-RS Image File Download File: FileDownloadService.java 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21.

package com.javatpoint.rest; import java.io.File; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; @Path("/files") public class FileDownloadService { private static final String FILE_PATH = "c:\\myimage.png"; @GET @Path("/image") @Produces("image/png") public Response getFile() { File file = new File(FILE_PATH); ResponseBuilder response = Response.ok((Object) file); response.header("Content-Disposition","attachment; filename=\"javatpoint_image.png\" ");

return response.build(); } }

File: web.xml Same as above example.

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.

Download Image File Click me to download this example

JAX-RS PDF File Download File: FileDownloadService.java 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20.

package com.javatpoint.rest; import java.io.File; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; @Path("/files") public class FileDownloadService { private static final String FILE_PATH = "c:\\mypdf.pdf"; @GET @Path("/pdf") @Produces("application/pdf") public Response getFile() { File file = new File(FILE_PATH); ResponseBuilder response = Response.ok((Object) file); response.header("Content-Disposition","attachment; filename=\"javatpoint_pdf.pdf\""); return response.build(); } }

File: web.xml Same as above example.

File: index.html 1.

Download PDF File Click me to download this example

RESTful JAX-RS File Upload Example Like download in previous page, we can easily upload a file such as image file, pdf file, excel file, text file etc. 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 using JAX-RS API, we are using jersey implementation.

Click me to download jersey jar files.

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 | 25

To upload file through jersey implementation, you need to provide extra configuration entry in web.xml file. 1. 2. 3. 4. 5.

jersey.config.server.provider.classnames org.glassfish.jersey.filter.LoggingFilter; org.glassfish.jersey.media.multipart.MultiPartFeature Let's see the complete code to upload file using RESTful JAX-RS API.

JAX-RS File Upload File: FileUploadService.java 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37.

package com.javatpoint.rest; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.FormDataParam; @Path("/files") public class FileUploadService { @POST @Path("/upload") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadFile( @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) { String fileLocation = "e://" + fileDetail.getFileName(); //saving file try { FileOutputStream out = new FileOutputStream(new File(fileLocation)); int read = 0; byte[] bytes = new byte[1024]; out = new FileOutputStream(new File(fileLocation)); while ((read = uploadedInputStream.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); out.close(); } catch (IOException e) {e.printStackTrace();} String output = "File successfully uploaded to : " + fileLocation; return Response.status(200).entity(output).build(); } }

File: web.xml 1.



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 | 26 2.

4. 5. Jersey REST Service 6. org.glassfish.jersey.servlet.ServletContainer 7. 8. jersey.config.server.provider.packages 9. com.javatpoint.rest 10. 11. 12. jersey.config.server.provider.classnames 13. org.glassfish.jersey.filter.LoggingFilter; 14. org.glassfish.jersey.media.multipart.MultiPartFeature 15. 16. 1 17. 18. 19. Jersey REST Service 20. /rest/* 21. 22.

File: index.html 1. 2. 3. 4. 5. 6. 7.

File Upload Example Select a file : Now run this application on server, you will see the following output: Output:

1.

File successfully uploaded to e://myimage.png Click me to download this example

View more...

Comments

Copyright © 2017 DATENPDF Inc.