分享

JAX

 yespon 2017-11-21

Hello readers. In this tutorial, we will show how to use the JAX-RS (RESTful) jar files to implement a simple Hello World Web Service in Java.

1. Introduction

JAX-RS stands for RESTful Web Services. JAX-RS is a set of APIs to develop the REST services. It is part of the Java EE6 and makes developers to develop the REST web application easily. JAX-RS makes extensive use of annotations available from Java SE 5 to simplify the coding and development of Java-based Web Services.

There are two main implementations of the JAX-RS API:

  • Jersey
  • RESTEasy
Fig. 1: JAX-RS Implementation

Fig. 1: JAX-RS Implementation

Following are the commonly used annotations in JAX-RS to map a resource as a web service resource.

AnnotationDescription
@PathThe @Path annotation’s value is a relative URI path indicating where the Java class will be hosted. For e.g.,/helloworld Developers can also embed variables in the URIs to make a URI path template. For e.g., Developers could ask for the name of a user and pass it to the application as a variable in the URI i.e. /helloworld/{username}.
@GETThis annotation indicates that the following method should respond to the HTTP GET request only. The HTTP Get request is used to fetch the resource.
@POSTThis annotation indicates that the following method should respond to the HTTP POST request only. The HTTP POST request is used to create/or update the resource.
@PUTThis annotation indicates that the following method should respond to the HTTP PUT request only. The HTTP PUT request is used to create a resource.
@DELETEThis annotation indicates that the following method should respond to the HTTP DELETE request only. The HTTP DELETE request is used to delete a resource.
@HEADThis annotation indicates that the following method should respond to the HTTP HEAD request only. The HTTP HEAD request is used to get the status of the method availability.
@Produces(MediaTypes.TEXT_PLAIN[,more –types])It defines which MIME type is delivered by a method annotated with @GET.
@Consumes( type[, more-types])It defines MIME type which is consumed by this method.
@PathParamUsed to inject values from the URL into a method parameter. For e.g., developers can inject the id of the resource into the method to get the correct object.

Now, open up the Eclipse IDE and let’s see how to develop a RESTful Hello World web application with JAX-RS!

2. Java Web Service Example

Here is a step-by-step guide for implementing the Web Service framework in Java.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 2: Web Service Application Project Structure

Fig. 2: Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 3: Create Maven Project

Fig. 3: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.

Fig. 4: Project Details

Fig. 4: Project Details

Select the ‘Maven Web App’ Archetype from the list of options and click next.

Fig. 5: Archetype Selection

Fig. 5: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 6: Archetype Parameters

Fig. 6: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

2    modelVersion>4.0.0modelVersion>
3    groupId>JavaWebServiceExamplegroupId>
4    artifactId>JavaWebServiceExampleartifactId>
5    version>0.0.1-SNAPSHOTversion>
6    packaging>warpackaging>
7project>

We can start adding the dependencies that developers want like Jersey, Junit etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

Here, we specify the dependencies for the Web Service framework. The rest dependencies will be automatically resolved by the Maven framework and the updated file will have the following code:

pom.xml

03    modelVersion>4.0.0modelVersion>
04    groupId>JavaWebServiceExamplegroupId>
05    artifactId>JavaWebServiceExampleartifactId>
06    packaging>warpackaging>
07    version>0.0.1-SNAPSHOTversion>
08    name>JavaWebServiceExample Maven Webappname>
09    url>http://maven.url>
10    dependencies>
11        
12        dependency>
13            groupId>com.sun.jerseygroupId>
14            artifactId>jersey-serverartifactId>
15            version>1.19version>
16        dependency>
17        
18        dependency>
19            groupId>com.sun.jerseygroupId>
20            artifactId>jersey-servletartifactId>
21            version>1.19version>
22        dependency>
23        
24        dependency>
25            groupId>javax.ws.rsgroupId>
26            artifactId>jsr311-apiartifactId>
27            version>1.1.1version>
28        dependency>
29        
30        dependency>
31            groupId>com.sun.jerseygroupId>
32            artifactId>jersey-clientartifactId>
33            version>1.19version>
34        dependency>
35    dependencies>
36    build>
37        finalName>${project.artifactId}finalName>
38    build>
39project>

3.2 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 7: Java Package Creation

Fig. 7: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.webservice.

Fig. 8: Java Package Name (com.jcg.webservice)

Fig. 8: Java Package Name (com.jcg.webservice)

Once the package is created in the application, we will need to create the controller class. Right-click on the newly created package: New -> Class.

Fig. 9: Java Class Creation

Fig. 9: Java Class Creation

A new pop window will open and enter the file name as: HelloWorldService. The sample Service class will be created inside the package: com.jcg.webservice.

Fig. 10: Java Class (HelloWorldService.java)

Fig. 10: Java Class (HelloWorldService.java)

3.2.1 Implementation of Service Class

Let’s see the simple code snippet that follows the JAX-RS implementation.

HelloWorldService.java

01package com.jcg.webservice;
02 
03import javax.ws.rs.GET;
04import javax.ws.rs.Path;
05import javax.ws.rs.PathParam;
06import javax.ws.rs.core.Response;
07 
08@Path('/hello')
09public class HelloWorldService {
10 
11    @GET
12    @Path('/{name}')
13    public Response getMsg(@PathParam('name') String name) {
14        String output = ' ' + '' + 'Java WebService Example' + ''  + '

'

15                + 'Hello ' + name + '
' + '';
16        return Response.status(200).entity(output).build();
17    }
18}

3.3 Configuration Application’s Deployment Descriptor

Let’s write the deployment descriptor involved in this application. In web.xml, register the com.sun.jersey.spi.container.servlet.ServletContainer and put the Jersey Service folder under the i.e.

1init-param>
2    param-name>com.sun.jersey.config.property.packagesparam-name>
3    param-value>com.jcg.webserviceparam-value>
4init-param>

Add the following code to it:

web.xml

01<>xml version='1.0' encoding='UTF-8'?>
04    xsi:schemaLocation='http://java./xml/ns/javaee       http://java./xml/ns/javaee/web-app_2_5.xsd' id='WebApp_ID' version='2.5'>
05    display-name>JavaWebServiceExampledisplay-name>
06    servlet>
07        servlet-name>jersey-serlvetservlet-name>
08        servlet-class>com.sun.jersey.spi.container.servlet.ServletContainerservlet-class>
09        init-param>
10            param-name>com.sun.jersey.config.property.packagesparam-name>
11            param-value>com.jcg.webserviceparam-value>
12        init-param>
13        load-on-startup>1load-on-startup>
14    servlet>
15    servlet-mapping>
16        servlet-name>jersey-serlvetservlet-name>
17        url-pattern>/rest/*url-pattern>
18    servlet-mapping>
19web-app>

4. Run the Application

As we are ready with all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Fig. 11: How to Deploy Application on Tomcat

Fig. 11: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it on the browser.

5. Project Demo

Open your favorite browser and hit the following URL. The default page will be displayed.

http://localhost:8085/JavaWebService/

Server name (localhost) and port (8085) may vary as per your Tomcat configuration. Developers can debug the example and see what happens after every step. Enjoy!

In web.xml we have specified the URL pattern as /rest/* and in HelloWorldService.java, we specified class level @path as /hello and method level @path as {name}. So the final URL should be http://localhost:8085/JavaWebService/rest/hello/java.

Test your REST service under the updated URL and you will get the following output.

Fig. 12: Welcome Page

Fig. 12: Welcome Page

That’s all for this post. Happy Learning!!

6. Conclusion

In this section, developers learned how to implement a simple Hello World Web Service in Java. Developers can download the sample application as an Eclipse project in the Downloads section. I hope this article served you with whatever developers were looking for.

7. Download the Eclipse Project

This was an example of Servlet Application Login.

Download
You can download the full source code of this example here: JavaWebServiceExample

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多