Jersey Java RESTful API on an Alibaba Cloud ECS Instance

简介: This tutorial describes how to develop apps with Jersey Java RESTful API on an Alibaba Cloud Elastic Compute Service instance.

By Aditya, Alibaba Cloud Tech Share Author. Tech Share is Alibaba Cloud's incentive program to encourage the sharing of technical knowledge and best practices within the cloud community.

With the increased adoption of digital technology, we see that same applications are typically available across different devices, notably on laptops, mobile phones, and TV. Most of the applications built or being built today are multi-tier. In a multi-tier application, you have clear distinctions of what each type can achieve. This makes sense from a business prospective as it significantly reduces costs. However, to cater to the different needs of the same data being available across different applications, we need to have a common place where we can access data with proper security rules.

From a developer's perspective, the increase need of data being replicated across different devices and the technology shift is happening very rapidly. We can't afford to take down the entire system just for a simple upgrade for a backend change. We should also be able to adapt to the newer technologies without much development effort. Taking all these conditions into account, we see that the REST framework gives us a clear abstraction between the other layers of how the data can be accessed across a different technology, such as mobile (Android and IOS) and web JavaScript Technologies.

Deploying a REST API onto an on-premises server is inefficient and time-consuming. Instead, we'll see how we can leverage Alibaba Cloud Elastic Compute Service to deploy our Java REST API and expose the service to internet. But before we even talk about deploying our API on to the cloud, we need to create one first. We will see how to create a Simple Jersey based Java REST API and test the API with selected tools.

Creating JAVA REST API

REST means "Representational State Transfer". REST was intended to create a decoupling between the server and the client, maintain reusable components, and can be replaced at any time. REST is stateless and you can implement cache on the server to improve performance and efficiency.

Now we will create a simple API which fetches the Employee Details & records the employee details.

Below are the complete tools I use for development.

  • Eclipse IDE for JAVA EE Developers
  • Latest Maven
  • Apache Tomcat web server 7
  • Insomnia REST Client

Setting Up the ECS Instance

Select Elastic Compute Instance from Products after logging into the Alibaba Cloud Console.

Create an Instance, preferably at the region closest to you. The following are the steps. For my server, I have selected the "Pay-as-you-go" model with the below configuration.

1

I will be using the Windows 2016 Data Center Image for my ECS instance. I have set the Networking, System Configurations, and other values to default. Click on Create Instance to continue.

Once the instance is created you will see something like this in your console.

2

Click on the ECS instance name and select security groups > configure rules > Add security group rules. Fill in the following information

3

Please note here that the 8080 is where my tomcat is deployed. You should change it to where your Apache Tomcat is actually deployed.

Connect the ECS Instance via RDP Protocol & we will do the further development using the windows VM Created.

Creating the API:

Download the latest "Eclipse IDE for JAVA EE Developers" and install.

  • You need to install the latest version of JDK & set the installation path to "JAVA_HOME" & also to the "Path" environment variables
  • You also need to install maven. It is so simple you need to download the latest binary distribution .zip and extract it & set the installation path to the "M2_HOME" & "Path" environment variables.

For the purpose of this article the code is provided as a zip file. Please download and import the project onto your eclipse workspace.

Download the Code Repository here: https://alicloud-common.oss-ap-southeast-1.aliyuncs.com/RESTCodeRepo.

You can import the code via "File > Import" and select "General" in the Dialog box.

Let’s see the imported code. You will see the below project structure in Eclipse.

4

We see the what included in the "pom.xml" the deployment descriptor for our complete project, holds the dependencies for our project.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.aditya.restapi</groupId>
    <artifactId>RESTfulExample</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>RESTfulExample Maven WebApplication</name>
    <url>http://maven.apache.org</url>

    <repositories>
        <repository>
            <id>maven2-repository.java.net</id>
            <name>Java.net Repository for Maven</name>
            <url>http://download.java.net/maven/2/</url>
            <layout>default</layout>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>1.8</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>1.8</version>
        </dependency>
        
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>1.8</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>RESTfulExample</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Model-version : This is the version which the current pom complies to, to support maven 3 we make the version to 4.0.0

Artifact Id, packaging, groupID, version, name : These are used while packaging and to describe the project while deployment.

Repositories : This tag consists of all the repositories the dependencies to pull from. You can specify multiple repositories under this. Here we specified the central public repository for java

Dependencies : This tag consists of all the dependencies which are needed for the project. We used jersey related jars for our API and a JUNIT jar

Build: the build tag contains the complete information of how the application will be packaged into the WAR format, naming & which version of maven assembly plugin will be used for packaging

We need a model to hold the data we receive and send, we have created a Employee.java model which holds the name, age, salary, company.

package com.aditya.model;

public class Employee {

    private String name;
    private String age;
    private int salary;
    private String company;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }
    public String getCompany() {
        return company;
    }
    public void setCompany(String company) {
        this.company = company;
    }
    @Override
    public String toString() {
        return "Employee [name=" + name + ", age=" + age + ", salary=" + salary + ", company=" + company + "]";
    }
}

This model consists of the getters, setters & toString() method for the getting, storing & display the information.

In the package "com.aditya.rest" for "JSONService.java" which has the complete code for REST API.

package com.aditya.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.aditya.model.Employee;

@Path("/json/empservice")
public class JSONService {

    @GET
    @Path("/get")
    @Produces(MediaType.APPLICATION_JSON)
    public Employee getEmpDetails() {

        Employee emp = new Employee();
        emp.setName("Aditya");
        emp.setCompany("ABC Corporation");
        emp.setAge("31");
        emp.setSalary(1000);

        return emp;

    }

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createEmpInJSON(Employee emp) {
        
        String result = "Employee saved : " + emp.toString();
        return Response.status(201).entity(result).build();
        
    }
    
}

We initially has the package declaration & we also notice that all the imports & annotations are imported from the Jersey jars.

The initial path maps the class with the map & methods are identified by @GET / @POST

@GET:

If we see the @GET is mapped to getEmpDetails() which returns an information of hardcoded data. The unmarshalling (JAVA Object to JSON) will happen automatically . This is one of the advantage of Jersey Servlet. We will see how.

@POST:

The @POST is mapped createEMPInJSON() which receives the marshalled Object from the request to Jersey Servlet to the emp object. The response is created with status 201 (Created) along with the result.

Web.xml

<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>Restful Web Application</display-name>

    <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.aditya.rest</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>

This is the deployment descriptor of the API. The display-name is obvious as it consists of the name of the application. This consists of the servlet-name we use, servlet-class consists of the fully qualified name of the servlet.

We also created the param-name & param-value gives the features we needed for the web application.

com.sun.jersey.api.json.POJOMappingFeature gives the capability of mapping the JSON to the java object.

The servlet-mapping maps the servlet feature with a specific URL Pattern.

Apache Tomcat 7:

Download the Windows installer at the official link
http://www-us.apache.org/dist/tomcat/tomcat-7/v7.0.85/bin/apache-tomcat-7.0.85.exe

execute the Tomcat7.exe and point the folder where you want the tomcat 7 to be installed.

Deploying and Testing the API:

5

Right Click on the servers section, select "New > Server"

6

Select "Tomcat 7 Server" select "Next"

7

You select "Browse" and point to the tomcat installation folder & the server will be created.

Right click on the project select "Run as " > "Run on server". Once your API is deployed, you will see the following status

8

Install the Insomnia Client, and create a new request and use the following URI:

GET : http://localhost:8080/RESTfulExample/rest/json/empservice/get

POST : http://localhost:8080/RESTfulExample/rest/json/empservice/post

You will see the following response

9

10

You can also access the same API using the public IP of the ECS Instance, There will no change with the API URL if we change that, The resultant URL will be

GET – http://:8080/RESTfulExample/rest/json/empservice/get

POST – http://:8080/RESTfulExample/rest/json/empservice/post

Additional Steps:

1.In Production, you can reduce the cost by using the Version 1709 Windows server Image which only gives the console based access, But it cuts a lot of software on your ECS Instance increasing the performance.

2.You should also use server load balancer for the API of we are planning to scale it up using multiple ECS images.

3.You can better have authentication in place like OAuth for the API to prevent abuse and better security.

4.You can also consider using Alibaba Cloud DNS and Anti-DDOS Pro for better security features for your API.

相关实践学习
2分钟自动化部署人生模拟器
本场景将带你借助云效流水线Flow实现人生模拟器小游戏的自动化部署
7天玩转云服务器
云服务器ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,可降低 IT 成本,提升运维效率。本课程手把手带你了解ECS、掌握基本操作、动手实操快照管理、镜像管理等。了解产品详情:&nbsp;https://www.aliyun.com/product/ecs
目录
相关文章
|
2天前
|
数据采集 存储 Java
Java爬虫获取微店店铺所有商品API接口设计与实现
本文介绍如何使用Java设计并实现一个爬虫程序,以获取微店店铺的所有商品信息。通过HttpClient发送HTTP请求,Jsoup解析HTML页面,提取商品名称、价格、图片链接等数据,并将其存储到本地文件或数据库中。文中详细描述了爬虫的设计思路、代码实现及注意事项,包括反爬虫机制、数据合法性和性能优化。此方法可帮助商家了解竞争对手,为消费者提供更全面的商品比较。
|
7天前
|
缓存 Java 应用服务中间件
java语言后台管理若依框架-登录提示404-接口异常-系统接口404异常如何处理-登录验证码不显示prod-api/captchaImage 404 (Not Found) 如何处理-解决方案优雅草卓伊凡
java语言后台管理若依框架-登录提示404-接口异常-系统接口404异常如何处理-登录验证码不显示prod-api/captchaImage 404 (Not Found) 如何处理-解决方案优雅草卓伊凡
34 5
|
2月前
|
JSON Java Apache
Java基础-常用API-Object类
继承是面向对象编程的重要特性,允许从已有类派生新类。Java采用单继承机制,默认所有类继承自Object类。Object类提供了多个常用方法,如`clone()`用于复制对象,`equals()`判断对象是否相等,`hashCode()`计算哈希码,`toString()`返回对象的字符串表示,`wait()`、`notify()`和`notifyAll()`用于线程同步,`finalize()`在对象被垃圾回收时调用。掌握这些方法有助于更好地理解和使用Java中的对象行为。
|
2月前
|
算法 Java API
如何使用Java开发获得淘宝商品描述API接口?
本文详细介绍如何使用Java开发调用淘宝商品描述API接口,涵盖从注册淘宝开放平台账号、阅读平台规则、创建应用并申请接口权限,到安装开发工具、配置开发环境、获取访问令牌,以及具体的Java代码实现和注意事项。通过遵循这些步骤,开发者可以高效地获取商品详情、描述及图片等信息,为项目和业务增添价值。
118 10
|
2月前
|
JSON JavaScript 前端开发
深入浅出Node.js:从零开始构建RESTful API
在数字化时代的浪潮中,后端开发作为连接用户与数据的桥梁,扮演着至关重要的角色。本文将引导您步入Node.js的奇妙世界,通过实践操作,掌握如何使用这一强大的JavaScript运行时环境构建高效、可扩展的RESTful API。我们将一同探索Express框架的使用,学习如何设计API端点,处理数据请求,并实现身份验证机制,最终部署我们的成果到云服务器上。无论您是初学者还是有一定基础的开发者,这篇文章都将为您打开一扇通往后端开发深层知识的大门。
71 12
|
2月前
|
Java API 开发者
Java中的Lambda表达式与Stream API的协同作用
在本文中,我们将探讨Java 8引入的Lambda表达式和Stream API如何改变我们处理集合和数组的方式。Lambda表达式提供了一种简洁的方法来表达代码块,而Stream API则允许我们对数据流进行高级操作,如过滤、映射和归约。通过结合使用这两种技术,我们可以以声明式的方式编写更简洁、更易于理解和维护的代码。本文将介绍Lambda表达式和Stream API的基本概念,并通过示例展示它们在实际项目中的应用。
|
3月前
|
XML JSON 缓存
深入理解RESTful API设计原则与实践
在现代软件开发中,构建高效、可扩展的应用程序接口(API)是至关重要的。本文旨在探讨RESTful API的核心设计理念,包括其基于HTTP协议的特性,以及如何在实际应用中遵循这些原则来优化API设计。我们将通过具体示例和最佳实践,展示如何创建易于理解、维护且性能优良的RESTful服务,从而提升前后端分离架构下的开发效率和用户体验。
|
3月前
|
安全 Java API
Java中的Lambda表达式与Stream API的高效结合####
探索Java编程中Lambda表达式与Stream API如何携手并进,提升数据处理效率,实现代码简洁性与功能性的双重飞跃。 ####
44 0
|
3月前
|
负载均衡 数据可视化 API
像素流送api ue多人访问需要什么显卡服务器
本文总结了关于像素流送技术的五大常见问题,包括是否支持Unity模型推流、UE多人访问的最大并发数、所需服务器配置、稳定性问题及API支持情况,旨在帮助开发者更好地理解和应用这一技术。
111 1
|
3月前
|
JSON 缓存 测试技术
构建高效RESTful API的后端实践指南####
本文将深入探讨如何设计并实现一个高效、可扩展且易于维护的RESTful API。不同于传统的摘要概述,本节将直接以行动指南的形式,列出构建RESTful API时必须遵循的核心原则与最佳实践,旨在为开发者提供一套直接可行的实施框架,快速提升API设计与开发能力。 ####

热门文章

最新文章