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
目录
相关文章
|
5天前
|
监控 Java 应用服务中间件
高级java面试---spring.factories文件的解析源码API机制
【11月更文挑战第20天】Spring Boot是一个用于快速构建基于Spring框架的应用程序的开源框架。它通过自动配置、起步依赖和内嵌服务器等特性,极大地简化了Spring应用的开发和部署过程。本文将深入探讨Spring Boot的背景历史、业务场景、功能点以及底层原理,并通过Java代码手写模拟Spring Boot的启动过程,特别是spring.factories文件的解析源码API机制。
18 2
|
9天前
|
SQL 缓存 测试技术
构建高性能RESTful API:最佳实践与避坑指南###
—— 本文深入探讨了构建高性能RESTful API的关键技术要点,从设计原则、状态码使用、版本控制到安全性考虑,旨在为开发者提供一套全面的最佳实践框架。通过避免常见的设计陷阱,本文将指导你如何优化API性能,提升用户体验,确保系统的稳定性和可扩展性。 ###
46 12
|
6天前
|
JSON JavaScript API
深入浅出Node.js:从零开始构建RESTful API
【10月更文挑战第39天】 在数字化时代的浪潮中,API(应用程序编程接口)已成为连接不同软件应用的桥梁。本文将带领读者从零基础出发,逐步深入Node.js的世界,最终实现一个功能完备的RESTful API。通过实践,我们将探索如何利用Node.js的异步特性和强大的生态系统来构建高效、可扩展的服务。准备好迎接代码和概念的碰撞,一起解锁后端开发的新篇章。
|
9天前
|
存储 API 开发者
深入理解RESTful API设计原则
本文探讨了RESTful API的设计原则,强调了其在现代Web服务中的重要性。通过分析状态表示转移(REST)的概念、核心约束以及最佳实践,本文旨在为开发者提供构建高效、可扩展和易于维护的API的指导。文章还讨论了常见的设计陷阱和如何避免它们,以确保API设计的健壮性和灵活性。
|
10天前
|
JSON 缓存 API
构建高效RESTful API的最佳实践
【10月更文挑战第34天】在数字时代的浪潮中,后端开发扮演着至关重要的角色。本文将带你深入探索如何构建高效的RESTful API,从设计原则到实际编码技巧,再到性能优化和错误处理,我们将一一解锁这些技能。你将学会如何打造一个既优雅又强大的后端服务,让你的应用程序在激烈的市场竞争中脱颖而出。那么,让我们一起踏上这段精彩的旅程吧!
26 2
|
12天前
|
缓存 监控 Java
如何运用JAVA开发API接口?
本文详细介绍了如何使用Java开发API接口,涵盖创建、实现、测试和部署接口的关键步骤。同时,讨论了接口的安全性设计和设计原则,帮助开发者构建高效、安全、易于维护的API接口。
35 4
|
12天前
|
XML JSON API
【PHP开发专栏】PHP RESTful API设计与开发
随着互联网技术的发展,前后端分离成为Web开发的主流模式。本文介绍RESTful API的基本概念、设计原则及在PHP中的实现方法。RESTful API是一种轻量级、无状态的接口设计风格,通过HTTP方法(GET、POST、PUT、DELETE)操作资源,使用JSON或XML格式传输数据。在PHP中,通过定义路由、创建控制器、处理HTTP请求和响应等步骤实现RESTful API,并强调了安全性的重要性。
20 2
|
14天前
|
存储 安全 API
深入理解RESTful API设计原则
本文旨在探讨RESTful API设计的基本原则和最佳实践,帮助开发者构建高效、可维护的Web服务。通过分析REST架构的核心概念,如资源、统一接口、无状态通信等,本文将指导读者如何设计符合REST原则的API,以及如何处理常见的设计挑战,如版本控制、错误处理和安全性问题。
|
16天前
|
存储 缓存 API
深入理解RESTful API设计原则
【10月更文挑战第28天】 在现代软件开发中,RESTful API已经成为了前后端分离架构下不可或缺的一部分。本文将探讨RESTful API的核心设计原则,包括资源导向、无状态性、统一的接口以及可缓存性等关键概念,并通过实例解析如何在实际应用中遵循这些原则来设计高效、可扩展的API。我们将深入了解REST架构风格的理论基础,并讨论其对提升系统互操作性和简化客户端实现的重要性。
50 3
|
17天前
|
JavaScript 中间件 API
Node.js进阶:Koa框架下的RESTful API设计与实现
【10月更文挑战第28天】本文介绍了如何在Koa框架下设计与实现RESTful API。首先概述了Koa框架的特点,接着讲解了RESTful API的设计原则,包括无状态和统一接口。最后,通过一个简单的博客系统示例,详细展示了如何使用Koa和koa-router实现常见的CRUD操作,包括获取、创建、更新和删除文章。
35 4